From 81e594d319a5e76549e8f4aa45c4200f67b3f646 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Fri, 5 Jun 2020 12:41:33 +0200 Subject: [PATCH 01/18] Dynamic server support --- .../resources/python/configuration.mustache | 32 ++++++++++++-- .../python/python-experimental/api.mustache | 42 ++++++++++++++++--- 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python/configuration.mustache b/modules/openapi-generator/src/main/resources/python/configuration.mustache index d1705eed25d2..a6df528280b4 100644 --- a/modules/openapi-generator/src/main/resources/python/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/python/configuration.mustache @@ -155,7 +155,7 @@ conf = {{{packageName}}}.Configuration( _default = None - def __init__(self, host="{{{basePath}}}", + def __init__(self, host=None, api_key=None, api_key_prefix=None, username=None, password=None, discard_unknown_keys=False, @@ -163,12 +163,22 @@ conf = {{{packageName}}}.Configuration( {{#hasHttpSignatureMethods}} signing_info=None, {{/hasHttpSignatureMethods}} + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, ): """Constructor """ - self.host = host + self._base_path = "{{{basePath}}}" if host is None else host """Default Base url """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default sever variables + """ self.temp_folder_path = None """Temp file folder for downloading files """ @@ -561,14 +571,14 @@ conf = {{{packageName}}}.Configuration( {{/servers}} ] - def get_host_from_settings(self, index, variables=None): + def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ variables = {} if variables is None else variables - servers = self.get_host_settings() + servers = self.get_host_settings() if servers is None else servers try: server = servers[index] @@ -595,3 +605,17 @@ conf = {{{packageName}}}.Configuration( url = url.replace("{" + variable_name + "}", used_value) return url + + @property + def host(self): + """Return generated host.""" + if self.server_index is None: + return self._base_path + + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache index 92e909165d6e..ebeeb57d87d2 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache @@ -105,7 +105,7 @@ class {{classname}}(object): Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -131,7 +131,7 @@ class {{classname}}(object): kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) {{#requiredParams}} kwargs['{{paramName}}'] = \ {{paramName}} @@ -160,7 +160,31 @@ class {{classname}}(object): {{#-first}} 'servers': [ {{/-first}} - '{{{url}}}'{{^-last}},{{/-last}} + { + 'url': "{{{url}}}", + 'description': "{{{description}}}{{^description}}No description provided{{/description}}", + {{#variables}} + {{#-first}} + 'variables': { + {{/-first}} + '{{{name}}}': { + 'description': "{{{description}}}{{^description}}No description provided{{/description}}", + 'default_value': "{{{defaultValue}}}", + {{#enumValues}} + {{#-first}} + 'enum_values': [ + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ] + {{/-last}} + {{/enumValues}} + }{{^-last}},{{/-last}} + {{#-last}} + } + {{/-last}} + {{/variables}} + }, {{#-last}} ] {{/-last}} @@ -348,7 +372,7 @@ class Endpoint(object): self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -447,7 +471,15 @@ class Endpoint(object): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( From 4985f2711ee994f75deb55d67a028c54defc0d8c Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Fri, 5 Jun 2020 12:47:33 +0200 Subject: [PATCH 02/18] regenerated --- .../petstore_api/configuration.py | 32 +++++++-- .../petstore_api/api/another_fake_api.py | 16 +++-- .../petstore_api/api/fake_api.py | 72 ++++++++++--------- .../api/fake_classname_tags_123_api.py | 16 +++-- .../petstore_api/api/pet_api.py | 48 +++++++------ .../petstore_api/api/store_api.py | 28 +++++--- .../petstore_api/api/user_api.py | 44 +++++++----- .../petstore_api/configuration.py | 32 +++++++-- .../petstore_api/configuration.py | 32 +++++++-- .../python/petstore_api/configuration.py | 32 +++++++-- .../petstore_api/api/another_fake_api.py | 16 +++-- .../petstore_api/api/default_api.py | 16 +++-- .../petstore_api/api/fake_api.py | 72 ++++++++++--------- .../api/fake_classname_tags_123_api.py | 16 +++-- .../petstore_api/api/pet_api.py | 68 +++++++++++------- .../petstore_api/api/store_api.py | 28 +++++--- .../petstore_api/api/user_api.py | 44 +++++++----- .../petstore_api/configuration.py | 32 +++++++-- 18 files changed, 440 insertions(+), 204 deletions(-) diff --git a/samples/client/petstore/python-asyncio/petstore_api/configuration.py b/samples/client/petstore/python-asyncio/petstore_api/configuration.py index 5c860e8c9547..2b17fd76f5a0 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/configuration.py +++ b/samples/client/petstore/python-asyncio/petstore_api/configuration.py @@ -109,17 +109,27 @@ class Configuration(object): _default = None - def __init__(self, host="http://petstore.swagger.io:80/v2", + def __init__(self, host=None, api_key=None, api_key_prefix=None, username=None, password=None, discard_unknown_keys=False, disabled_client_side_validations="", + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, ): """Constructor """ - self.host = host + self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host """Default Base url """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default sever variables + """ self.temp_folder_path = None """Temp file folder for downloading files """ @@ -432,14 +442,14 @@ def get_host_settings(self): } ] - def get_host_from_settings(self, index, variables=None): + def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ variables = {} if variables is None else variables - servers = self.get_host_settings() + servers = self.get_host_settings() if servers is None else servers try: server = servers[index] @@ -466,3 +476,17 @@ def get_host_from_settings(self, index, variables=None): url = url.replace("{" + variable_name + "}", used_value) return url + + @property + def host(self): + """Return generated host.""" + if self.server_index is None: + return self._base_path + + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py index 49f603489978..5b750a442d10 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py @@ -84,7 +84,7 @@ def __call_123_test_special_tags( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -110,7 +110,7 @@ def __call_123_test_special_tags( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -221,7 +221,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -320,7 +320,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py index 3f2e1ae4bd94..44645ad09961 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -90,7 +90,7 @@ def __create_xml_item( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -116,7 +116,7 @@ def __create_xml_item( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['xml_item'] = \ xml_item return self.call_with_http_info(**kwargs) @@ -209,7 +209,7 @@ def __fake_outer_boolean_serialize( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -235,7 +235,7 @@ def __fake_outer_boolean_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.fake_outer_boolean_serialize = Endpoint( @@ -319,7 +319,7 @@ def __fake_outer_composite_serialize( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -345,7 +345,7 @@ def __fake_outer_composite_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.fake_outer_composite_serialize = Endpoint( @@ -429,7 +429,7 @@ def __fake_outer_enum_serialize( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -455,7 +455,7 @@ def __fake_outer_enum_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.fake_outer_enum_serialize = Endpoint( @@ -539,7 +539,7 @@ def __fake_outer_number_serialize( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -565,7 +565,7 @@ def __fake_outer_number_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.fake_outer_number_serialize = Endpoint( @@ -649,7 +649,7 @@ def __fake_outer_string_serialize( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -675,7 +675,7 @@ def __fake_outer_string_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.fake_outer_string_serialize = Endpoint( @@ -761,7 +761,7 @@ def __test_body_with_file_schema( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -787,7 +787,7 @@ def __test_body_with_file_schema( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -878,7 +878,7 @@ def __test_body_with_query_params( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -904,7 +904,7 @@ def __test_body_with_query_params( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['query'] = \ query kwargs['body'] = \ @@ -1002,7 +1002,7 @@ def __test_client_model( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1028,7 +1028,7 @@ def __test_client_model( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -1128,7 +1128,7 @@ def __test_endpoint_enums_length_one( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1154,7 +1154,7 @@ def __test_endpoint_enums_length_one( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['query_integer'] = \ query_integer kwargs['query_string'] = \ @@ -1316,7 +1316,7 @@ def __test_endpoint_parameters( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1342,7 +1342,7 @@ def __test_endpoint_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['number'] = \ number kwargs['double'] = \ @@ -1563,7 +1563,7 @@ def __test_enum_parameters( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1589,7 +1589,7 @@ def __test_enum_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.test_enum_parameters = Endpoint( @@ -1772,7 +1772,7 @@ def __test_group_parameters( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1798,7 +1798,7 @@ def __test_group_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['required_string_group'] = \ required_string_group kwargs['required_boolean_group'] = \ @@ -1917,7 +1917,7 @@ def __test_inline_additional_properties( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1943,7 +1943,7 @@ def __test_inline_additional_properties( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['param'] = \ param return self.call_with_http_info(**kwargs) @@ -2034,7 +2034,7 @@ def __test_json_form_data( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -2060,7 +2060,7 @@ def __test_json_form_data( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['param'] = \ param kwargs['param2'] = \ @@ -2178,7 +2178,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -2277,7 +2277,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py index 22b66a6a6c00..43c6862ae4bb 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py @@ -84,7 +84,7 @@ def __test_classname( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -110,7 +110,7 @@ def __test_classname( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -223,7 +223,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -322,7 +322,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py index d917cb3cd678..8f8c9ded5ab1 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -84,7 +84,7 @@ def __add_pet( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -110,7 +110,7 @@ def __add_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -203,7 +203,7 @@ def __delete_pet( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -229,7 +229,7 @@ def __delete_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -325,7 +325,7 @@ def __find_pets_by_status( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -351,7 +351,7 @@ def __find_pets_by_status( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['status'] = \ status return self.call_with_http_info(**kwargs) @@ -453,7 +453,7 @@ def __find_pets_by_tags( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -479,7 +479,7 @@ def __find_pets_by_tags( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['tags'] = \ tags return self.call_with_http_info(**kwargs) @@ -574,7 +574,7 @@ def __get_pet_by_id( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -600,7 +600,7 @@ def __get_pet_by_id( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -693,7 +693,7 @@ def __update_pet( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -719,7 +719,7 @@ def __update_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -813,7 +813,7 @@ def __update_pet_with_form( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -839,7 +839,7 @@ def __update_pet_with_form( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -944,7 +944,7 @@ def __upload_file( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -970,7 +970,7 @@ def __upload_file( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -1083,7 +1083,7 @@ def __upload_file_with_required_file( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1109,7 +1109,7 @@ def __upload_file_with_required_file( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_id'] = \ pet_id kwargs['required_file'] = \ @@ -1236,7 +1236,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -1335,7 +1335,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py index bd4c0e0a25ee..c6e6087eef56 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -84,7 +84,7 @@ def __delete_order( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -110,7 +110,7 @@ def __delete_order( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['order_id'] = \ order_id return self.call_with_http_info(**kwargs) @@ -196,7 +196,7 @@ def __get_inventory( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -222,7 +222,7 @@ def __get_inventory( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.get_inventory = Endpoint( @@ -306,7 +306,7 @@ def __get_order_by_id( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -332,7 +332,7 @@ def __get_order_by_id( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['order_id'] = \ order_id return self.call_with_http_info(**kwargs) @@ -429,7 +429,7 @@ def __place_order( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -455,7 +455,7 @@ def __place_order( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -565,7 +565,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -664,7 +664,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py index f313a2303546..80d8fd4fba24 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py @@ -84,7 +84,7 @@ def __create_user( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -110,7 +110,7 @@ def __create_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -197,7 +197,7 @@ def __create_users_with_array_input( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -223,7 +223,7 @@ def __create_users_with_array_input( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -310,7 +310,7 @@ def __create_users_with_list_input( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -336,7 +336,7 @@ def __create_users_with_list_input( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -424,7 +424,7 @@ def __delete_user( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -450,7 +450,7 @@ def __delete_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['username'] = \ username return self.call_with_http_info(**kwargs) @@ -538,7 +538,7 @@ def __get_user_by_name( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -564,7 +564,7 @@ def __get_user_by_name( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['username'] = \ username return self.call_with_http_info(**kwargs) @@ -657,7 +657,7 @@ def __login_user( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -683,7 +683,7 @@ def __login_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['username'] = \ username kwargs['password'] = \ @@ -779,7 +779,7 @@ def __logout_user( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -805,7 +805,7 @@ def __logout_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.logout_user = Endpoint( @@ -887,7 +887,7 @@ def __update_user( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -913,7 +913,7 @@ def __update_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['username'] = \ username kwargs['body'] = \ @@ -1028,7 +1028,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -1127,7 +1127,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/client/petstore/python-experimental/petstore_api/configuration.py b/samples/client/petstore/python-experimental/petstore_api/configuration.py index 18085f8b7485..c0a712a8104e 100644 --- a/samples/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/client/petstore/python-experimental/petstore_api/configuration.py @@ -110,17 +110,27 @@ class Configuration(object): _default = None - def __init__(self, host="http://petstore.swagger.io:80/v2", + def __init__(self, host=None, api_key=None, api_key_prefix=None, username=None, password=None, discard_unknown_keys=False, disabled_client_side_validations="", + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, ): """Constructor """ - self.host = host + self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host """Default Base url """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default sever variables + """ self.temp_folder_path = None """Temp file folder for downloading files """ @@ -436,14 +446,14 @@ def get_host_settings(self): } ] - def get_host_from_settings(self, index, variables=None): + def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ variables = {} if variables is None else variables - servers = self.get_host_settings() + servers = self.get_host_settings() if servers is None else servers try: server = servers[index] @@ -470,3 +480,17 @@ def get_host_from_settings(self, index, variables=None): url = url.replace("{" + variable_name + "}", used_value) return url + + @property + def host(self): + """Return generated host.""" + if self.server_index is None: + return self._base_path + + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/samples/client/petstore/python-tornado/petstore_api/configuration.py b/samples/client/petstore/python-tornado/petstore_api/configuration.py index 18085f8b7485..c0a712a8104e 100644 --- a/samples/client/petstore/python-tornado/petstore_api/configuration.py +++ b/samples/client/petstore/python-tornado/petstore_api/configuration.py @@ -110,17 +110,27 @@ class Configuration(object): _default = None - def __init__(self, host="http://petstore.swagger.io:80/v2", + def __init__(self, host=None, api_key=None, api_key_prefix=None, username=None, password=None, discard_unknown_keys=False, disabled_client_side_validations="", + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, ): """Constructor """ - self.host = host + self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host """Default Base url """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default sever variables + """ self.temp_folder_path = None """Temp file folder for downloading files """ @@ -436,14 +446,14 @@ def get_host_settings(self): } ] - def get_host_from_settings(self, index, variables=None): + def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ variables = {} if variables is None else variables - servers = self.get_host_settings() + servers = self.get_host_settings() if servers is None else servers try: server = servers[index] @@ -470,3 +480,17 @@ def get_host_from_settings(self, index, variables=None): url = url.replace("{" + variable_name + "}", used_value) return url + + @property + def host(self): + """Return generated host.""" + if self.server_index is None: + return self._base_path + + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index 18085f8b7485..c0a712a8104e 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -110,17 +110,27 @@ class Configuration(object): _default = None - def __init__(self, host="http://petstore.swagger.io:80/v2", + def __init__(self, host=None, api_key=None, api_key_prefix=None, username=None, password=None, discard_unknown_keys=False, disabled_client_side_validations="", + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, ): """Constructor """ - self.host = host + self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host """Default Base url """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default sever variables + """ self.temp_folder_path = None """Temp file folder for downloading files """ @@ -436,14 +446,14 @@ def get_host_settings(self): } ] - def get_host_from_settings(self, index, variables=None): + def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ variables = {} if variables is None else variables - servers = self.get_host_settings() + servers = self.get_host_settings() if servers is None else servers try: server = servers[index] @@ -470,3 +480,17 @@ def get_host_from_settings(self, index, variables=None): url = url.replace("{" + variable_name + "}", used_value) return url + + @property + def host(self): + """Return generated host.""" + if self.server_index is None: + return self._base_path + + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py index 7aebc264b071..28cec2307fea 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py @@ -84,7 +84,7 @@ def __call_123_test_special_tags( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -110,7 +110,7 @@ def __call_123_test_special_tags( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['client_client'] = \ client_client return self.call_with_http_info(**kwargs) @@ -221,7 +221,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -320,7 +320,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py index 65d9c2178a80..031ededd4bef 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py @@ -80,7 +80,7 @@ def __foo_get( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -106,7 +106,7 @@ def __foo_get( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.foo_get = Endpoint( @@ -207,7 +207,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -306,7 +306,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py index 687d23eecc4a..c82a150111f0 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -85,7 +85,7 @@ def __fake_health_get( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -111,7 +111,7 @@ def __fake_health_get( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.fake_health_get = Endpoint( @@ -191,7 +191,7 @@ def __fake_outer_boolean_serialize( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -217,7 +217,7 @@ def __fake_outer_boolean_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.fake_outer_boolean_serialize = Endpoint( @@ -303,7 +303,7 @@ def __fake_outer_composite_serialize( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -329,7 +329,7 @@ def __fake_outer_composite_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.fake_outer_composite_serialize = Endpoint( @@ -415,7 +415,7 @@ def __fake_outer_number_serialize( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -441,7 +441,7 @@ def __fake_outer_number_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.fake_outer_number_serialize = Endpoint( @@ -527,7 +527,7 @@ def __fake_outer_string_serialize( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -553,7 +553,7 @@ def __fake_outer_string_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.fake_outer_string_serialize = Endpoint( @@ -637,7 +637,7 @@ def __get_array_of_enums( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -663,7 +663,7 @@ def __get_array_of_enums( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.get_array_of_enums = Endpoint( @@ -745,7 +745,7 @@ def __test_body_with_file_schema( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -771,7 +771,7 @@ def __test_body_with_file_schema( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['file_schema_test_class_file_schema_test_class'] = \ file_schema_test_class_file_schema_test_class return self.call_with_http_info(**kwargs) @@ -862,7 +862,7 @@ def __test_body_with_query_params( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -888,7 +888,7 @@ def __test_body_with_query_params( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['query'] = \ query kwargs['user_user'] = \ @@ -986,7 +986,7 @@ def __test_client_model( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1012,7 +1012,7 @@ def __test_client_model( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['client_client'] = \ client_client return self.call_with_http_info(**kwargs) @@ -1120,7 +1120,7 @@ def __test_endpoint_parameters( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1146,7 +1146,7 @@ def __test_endpoint_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['number'] = \ number kwargs['double'] = \ @@ -1367,7 +1367,7 @@ def __test_enum_parameters( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1393,7 +1393,7 @@ def __test_enum_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.test_enum_parameters = Endpoint( @@ -1576,7 +1576,7 @@ def __test_group_parameters( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1602,7 +1602,7 @@ def __test_group_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['required_string_group'] = \ required_string_group kwargs['required_boolean_group'] = \ @@ -1723,7 +1723,7 @@ def __test_inline_additional_properties( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1749,7 +1749,7 @@ def __test_inline_additional_properties( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['request_body'] = \ request_body return self.call_with_http_info(**kwargs) @@ -1840,7 +1840,7 @@ def __test_json_form_data( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1866,7 +1866,7 @@ def __test_json_form_data( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['param'] = \ param kwargs['param2'] = \ @@ -1973,7 +1973,7 @@ def __test_query_parameter_collection_format( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1999,7 +1999,7 @@ def __test_query_parameter_collection_format( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pipe'] = \ pipe kwargs['ioutil'] = \ @@ -2144,7 +2144,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -2243,7 +2243,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py index e22f47b416c0..fa7e0c2dec10 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py @@ -84,7 +84,7 @@ def __test_classname( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -110,7 +110,7 @@ def __test_classname( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['client_client'] = \ client_client return self.call_with_http_info(**kwargs) @@ -223,7 +223,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -322,7 +322,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py index 9ca9a64f8e2d..2a7a458e884a 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -84,7 +84,7 @@ def __add_pet( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -110,7 +110,7 @@ def __add_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_pet'] = \ pet_pet return self.call_with_http_info(**kwargs) @@ -126,8 +126,14 @@ def __add_pet( 'operation_id': 'add_pet', 'http_method': 'POST', 'servers': [ - 'http://petstore.swagger.io/v2', - 'http://path-server-test.petstore.local/v2' + { + 'url': "http://petstore.swagger.io/v2", + 'description': "No description provided", + }, + { + 'url': "http://path-server-test.petstore.local/v2", + 'description': "No description provided", + }, ] }, params_map={ @@ -207,7 +213,7 @@ def __delete_pet( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -233,7 +239,7 @@ def __delete_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -329,7 +335,7 @@ def __find_pets_by_status( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -355,7 +361,7 @@ def __find_pets_by_status( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['status'] = \ status return self.call_with_http_info(**kwargs) @@ -458,7 +464,7 @@ def __find_pets_by_tags( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -484,7 +490,7 @@ def __find_pets_by_tags( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['tags'] = \ tags return self.call_with_http_info(**kwargs) @@ -580,7 +586,7 @@ def __get_pet_by_id( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -606,7 +612,7 @@ def __get_pet_by_id( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -699,7 +705,7 @@ def __update_pet( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -725,7 +731,7 @@ def __update_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_pet'] = \ pet_pet return self.call_with_http_info(**kwargs) @@ -741,8 +747,14 @@ def __update_pet( 'operation_id': 'update_pet', 'http_method': 'PUT', 'servers': [ - 'http://petstore.swagger.io/v2', - 'http://path-server-test.petstore.local/v2' + { + 'url': "http://petstore.swagger.io/v2", + 'description': "No description provided", + }, + { + 'url': "http://path-server-test.petstore.local/v2", + 'description': "No description provided", + }, ] }, params_map={ @@ -823,7 +835,7 @@ def __update_pet_with_form( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -849,7 +861,7 @@ def __update_pet_with_form( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -953,7 +965,7 @@ def __upload_file( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -979,7 +991,7 @@ def __upload_file( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -1086,7 +1098,7 @@ def __upload_file_with_required_file( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -1112,7 +1124,7 @@ def __upload_file_with_required_file( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['pet_id'] = \ pet_id kwargs['required_file'] = \ @@ -1239,7 +1251,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -1338,7 +1350,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py index 5bd88ecdca16..148b90ecd607 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -84,7 +84,7 @@ def __delete_order( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -110,7 +110,7 @@ def __delete_order( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['order_id'] = \ order_id return self.call_with_http_info(**kwargs) @@ -196,7 +196,7 @@ def __get_inventory( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -222,7 +222,7 @@ def __get_inventory( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.get_inventory = Endpoint( @@ -306,7 +306,7 @@ def __get_order_by_id( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -332,7 +332,7 @@ def __get_order_by_id( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['order_id'] = \ order_id return self.call_with_http_info(**kwargs) @@ -429,7 +429,7 @@ def __place_order( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -455,7 +455,7 @@ def __place_order( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['order_order'] = \ order_order return self.call_with_http_info(**kwargs) @@ -567,7 +567,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -666,7 +666,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py index 46f1fdf79cae..2c9f2eae8f22 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py @@ -84,7 +84,7 @@ def __create_user( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -110,7 +110,7 @@ def __create_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['user_user'] = \ user_user return self.call_with_http_info(**kwargs) @@ -199,7 +199,7 @@ def __create_users_with_array_input( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -225,7 +225,7 @@ def __create_users_with_array_input( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['user_user'] = \ user_user return self.call_with_http_info(**kwargs) @@ -314,7 +314,7 @@ def __create_users_with_list_input( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -340,7 +340,7 @@ def __create_users_with_list_input( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['user_user'] = \ user_user return self.call_with_http_info(**kwargs) @@ -430,7 +430,7 @@ def __delete_user( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -456,7 +456,7 @@ def __delete_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['username'] = \ username return self.call_with_http_info(**kwargs) @@ -544,7 +544,7 @@ def __get_user_by_name( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -570,7 +570,7 @@ def __get_user_by_name( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['username'] = \ username return self.call_with_http_info(**kwargs) @@ -663,7 +663,7 @@ def __login_user( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -689,7 +689,7 @@ def __login_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['username'] = \ username kwargs['password'] = \ @@ -785,7 +785,7 @@ def __logout_user( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -811,7 +811,7 @@ def __logout_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) return self.call_with_http_info(**kwargs) self.logout_user = Endpoint( @@ -893,7 +893,7 @@ def __update_user( Default is True. _host_index (int): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -919,7 +919,7 @@ def __update_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index', None) kwargs['username'] = \ username kwargs['user_user'] = \ @@ -1036,7 +1036,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -1135,7 +1135,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'] + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py index 850cb907b09f..3e4a25650fda 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py @@ -151,18 +151,28 @@ class Configuration(object): _default = None - def __init__(self, host="http://petstore.swagger.io:80/v2", + def __init__(self, host=None, api_key=None, api_key_prefix=None, username=None, password=None, discard_unknown_keys=False, disabled_client_side_validations="", signing_info=None, + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, ): """Constructor """ - self.host = host + self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host """Default Base url """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default sever variables + """ self.temp_folder_path = None """Temp file folder for downloading files """ @@ -535,14 +545,14 @@ def get_host_settings(self): } ] - def get_host_from_settings(self, index, variables=None): + def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value :return: URL based on host settings """ variables = {} if variables is None else variables - servers = self.get_host_settings() + servers = self.get_host_settings() if servers is None else servers try: server = servers[index] @@ -569,3 +579,17 @@ def get_host_from_settings(self, index, variables=None): url = url.replace("{" + variable_name + "}", used_value) return url + + @property + def host(self): + """Return generated host.""" + if self.server_index is None: + return self._base_path + + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None From 1fd2e65794a3996f358ce868265c8b5df51cb2d5 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Fri, 5 Jun 2020 14:24:09 +0200 Subject: [PATCH 03/18] Apply suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Thomas Hervé --- .../src/main/resources/python/configuration.mustache | 3 ++- .../src/main/resources/python/python-experimental/api.mustache | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python/configuration.mustache b/modules/openapi-generator/src/main/resources/python/configuration.mustache index a6df528280b4..8b087a49e0fe 100644 --- a/modules/openapi-generator/src/main/resources/python/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/python/configuration.mustache @@ -177,7 +177,7 @@ conf = {{{packageName}}}.Configuration( """ self.server_variables = server_variables or {} self.server_operation_variables = server_operation_variables or {} - """Default sever variables + """Default server variables """ self.temp_folder_path = None """Temp file folder for downloading files @@ -575,6 +575,7 @@ conf = {{{packageName}}}.Configuration( """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value + :param servers: host settings for the endpoint :return: URL based on host settings """ variables = {} if variables is None else variables diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache index ebeeb57d87d2..d05f7af3869a 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache @@ -131,7 +131,7 @@ class {{classname}}(object): kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') {{#requiredParams}} kwargs['{{paramName}}'] = \ {{paramName}} From 6caf66f430e8317c925794022ee1e8de9fcf6cbc Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Fri, 5 Jun 2020 14:27:14 +0200 Subject: [PATCH 04/18] regenerated --- .../petstore_api/configuration.py | 3 +- .../petstore_api/api/another_fake_api.py | 2 +- .../petstore_api/api/fake_api.py | 30 +++++++++---------- .../api/fake_classname_tags_123_api.py | 2 +- .../petstore_api/api/pet_api.py | 18 +++++------ .../petstore_api/api/store_api.py | 8 ++--- .../petstore_api/api/user_api.py | 16 +++++----- .../petstore_api/configuration.py | 3 +- .../petstore_api/configuration.py | 3 +- .../python/petstore_api/configuration.py | 3 +- .../petstore_api/api/another_fake_api.py | 2 +- .../petstore_api/api/default_api.py | 2 +- .../petstore_api/api/fake_api.py | 30 +++++++++---------- .../api/fake_classname_tags_123_api.py | 2 +- .../petstore_api/api/pet_api.py | 18 +++++------ .../petstore_api/api/store_api.py | 8 ++--- .../petstore_api/api/user_api.py | 16 +++++----- .../petstore_api/configuration.py | 3 +- 18 files changed, 87 insertions(+), 82 deletions(-) diff --git a/samples/client/petstore/python-asyncio/petstore_api/configuration.py b/samples/client/petstore/python-asyncio/petstore_api/configuration.py index 2b17fd76f5a0..08f439a4b683 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/configuration.py +++ b/samples/client/petstore/python-asyncio/petstore_api/configuration.py @@ -128,7 +128,7 @@ def __init__(self, host=None, """ self.server_variables = server_variables or {} self.server_operation_variables = server_operation_variables or {} - """Default sever variables + """Default server variables """ self.temp_folder_path = None """Temp file folder for downloading files @@ -446,6 +446,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value + :param servers: host settings for the endpoint :return: URL based on host settings """ variables = {} if variables is None else variables diff --git a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py index 5b750a442d10..0117dc0c865f 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py @@ -110,7 +110,7 @@ def __call_123_test_special_tags( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['body'] = \ body return self.call_with_http_info(**kwargs) diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py index 44645ad09961..7fa17729e516 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -116,7 +116,7 @@ def __create_xml_item( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['xml_item'] = \ xml_item return self.call_with_http_info(**kwargs) @@ -235,7 +235,7 @@ def __fake_outer_boolean_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.fake_outer_boolean_serialize = Endpoint( @@ -345,7 +345,7 @@ def __fake_outer_composite_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.fake_outer_composite_serialize = Endpoint( @@ -455,7 +455,7 @@ def __fake_outer_enum_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.fake_outer_enum_serialize = Endpoint( @@ -565,7 +565,7 @@ def __fake_outer_number_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.fake_outer_number_serialize = Endpoint( @@ -675,7 +675,7 @@ def __fake_outer_string_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.fake_outer_string_serialize = Endpoint( @@ -787,7 +787,7 @@ def __test_body_with_file_schema( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -904,7 +904,7 @@ def __test_body_with_query_params( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['query'] = \ query kwargs['body'] = \ @@ -1028,7 +1028,7 @@ def __test_client_model( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -1154,7 +1154,7 @@ def __test_endpoint_enums_length_one( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['query_integer'] = \ query_integer kwargs['query_string'] = \ @@ -1342,7 +1342,7 @@ def __test_endpoint_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['number'] = \ number kwargs['double'] = \ @@ -1589,7 +1589,7 @@ def __test_enum_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.test_enum_parameters = Endpoint( @@ -1798,7 +1798,7 @@ def __test_group_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['required_string_group'] = \ required_string_group kwargs['required_boolean_group'] = \ @@ -1943,7 +1943,7 @@ def __test_inline_additional_properties( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['param'] = \ param return self.call_with_http_info(**kwargs) @@ -2060,7 +2060,7 @@ def __test_json_form_data( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['param'] = \ param kwargs['param2'] = \ diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py index 43c6862ae4bb..c54e632838ed 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py @@ -110,7 +110,7 @@ def __test_classname( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['body'] = \ body return self.call_with_http_info(**kwargs) diff --git a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py index 8f8c9ded5ab1..2469be4ef084 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -110,7 +110,7 @@ def __add_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -229,7 +229,7 @@ def __delete_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -351,7 +351,7 @@ def __find_pets_by_status( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['status'] = \ status return self.call_with_http_info(**kwargs) @@ -479,7 +479,7 @@ def __find_pets_by_tags( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['tags'] = \ tags return self.call_with_http_info(**kwargs) @@ -600,7 +600,7 @@ def __get_pet_by_id( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -719,7 +719,7 @@ def __update_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -839,7 +839,7 @@ def __update_pet_with_form( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -970,7 +970,7 @@ def __upload_file( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -1109,7 +1109,7 @@ def __upload_file_with_required_file( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_id'] = \ pet_id kwargs['required_file'] = \ diff --git a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py index c6e6087eef56..b6728a637d29 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -110,7 +110,7 @@ def __delete_order( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['order_id'] = \ order_id return self.call_with_http_info(**kwargs) @@ -222,7 +222,7 @@ def __get_inventory( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.get_inventory = Endpoint( @@ -332,7 +332,7 @@ def __get_order_by_id( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['order_id'] = \ order_id return self.call_with_http_info(**kwargs) @@ -455,7 +455,7 @@ def __place_order( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['body'] = \ body return self.call_with_http_info(**kwargs) diff --git a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py index 80d8fd4fba24..c34fab733969 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py @@ -110,7 +110,7 @@ def __create_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -223,7 +223,7 @@ def __create_users_with_array_input( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -336,7 +336,7 @@ def __create_users_with_list_input( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['body'] = \ body return self.call_with_http_info(**kwargs) @@ -450,7 +450,7 @@ def __delete_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['username'] = \ username return self.call_with_http_info(**kwargs) @@ -564,7 +564,7 @@ def __get_user_by_name( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['username'] = \ username return self.call_with_http_info(**kwargs) @@ -683,7 +683,7 @@ def __login_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['username'] = \ username kwargs['password'] = \ @@ -805,7 +805,7 @@ def __logout_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.logout_user = Endpoint( @@ -913,7 +913,7 @@ def __update_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['username'] = \ username kwargs['body'] = \ diff --git a/samples/client/petstore/python-experimental/petstore_api/configuration.py b/samples/client/petstore/python-experimental/petstore_api/configuration.py index c0a712a8104e..1f03df65feff 100644 --- a/samples/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/client/petstore/python-experimental/petstore_api/configuration.py @@ -129,7 +129,7 @@ def __init__(self, host=None, """ self.server_variables = server_variables or {} self.server_operation_variables = server_operation_variables or {} - """Default sever variables + """Default server variables """ self.temp_folder_path = None """Temp file folder for downloading files @@ -450,6 +450,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value + :param servers: host settings for the endpoint :return: URL based on host settings """ variables = {} if variables is None else variables diff --git a/samples/client/petstore/python-tornado/petstore_api/configuration.py b/samples/client/petstore/python-tornado/petstore_api/configuration.py index c0a712a8104e..1f03df65feff 100644 --- a/samples/client/petstore/python-tornado/petstore_api/configuration.py +++ b/samples/client/petstore/python-tornado/petstore_api/configuration.py @@ -129,7 +129,7 @@ def __init__(self, host=None, """ self.server_variables = server_variables or {} self.server_operation_variables = server_operation_variables or {} - """Default sever variables + """Default server variables """ self.temp_folder_path = None """Temp file folder for downloading files @@ -450,6 +450,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value + :param servers: host settings for the endpoint :return: URL based on host settings """ variables = {} if variables is None else variables diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index c0a712a8104e..1f03df65feff 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -129,7 +129,7 @@ def __init__(self, host=None, """ self.server_variables = server_variables or {} self.server_operation_variables = server_operation_variables or {} - """Default sever variables + """Default server variables """ self.temp_folder_path = None """Temp file folder for downloading files @@ -450,6 +450,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value + :param servers: host settings for the endpoint :return: URL based on host settings """ variables = {} if variables is None else variables diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py index 28cec2307fea..5d8d22d67429 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py @@ -110,7 +110,7 @@ def __call_123_test_special_tags( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['client_client'] = \ client_client return self.call_with_http_info(**kwargs) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py index 031ededd4bef..e17584ef244e 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py @@ -106,7 +106,7 @@ def __foo_get( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.foo_get = Endpoint( diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py index c82a150111f0..8982177cced4 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -111,7 +111,7 @@ def __fake_health_get( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.fake_health_get = Endpoint( @@ -217,7 +217,7 @@ def __fake_outer_boolean_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.fake_outer_boolean_serialize = Endpoint( @@ -329,7 +329,7 @@ def __fake_outer_composite_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.fake_outer_composite_serialize = Endpoint( @@ -441,7 +441,7 @@ def __fake_outer_number_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.fake_outer_number_serialize = Endpoint( @@ -553,7 +553,7 @@ def __fake_outer_string_serialize( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.fake_outer_string_serialize = Endpoint( @@ -663,7 +663,7 @@ def __get_array_of_enums( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.get_array_of_enums = Endpoint( @@ -771,7 +771,7 @@ def __test_body_with_file_schema( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['file_schema_test_class_file_schema_test_class'] = \ file_schema_test_class_file_schema_test_class return self.call_with_http_info(**kwargs) @@ -888,7 +888,7 @@ def __test_body_with_query_params( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['query'] = \ query kwargs['user_user'] = \ @@ -1012,7 +1012,7 @@ def __test_client_model( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['client_client'] = \ client_client return self.call_with_http_info(**kwargs) @@ -1146,7 +1146,7 @@ def __test_endpoint_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['number'] = \ number kwargs['double'] = \ @@ -1393,7 +1393,7 @@ def __test_enum_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.test_enum_parameters = Endpoint( @@ -1602,7 +1602,7 @@ def __test_group_parameters( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['required_string_group'] = \ required_string_group kwargs['required_boolean_group'] = \ @@ -1749,7 +1749,7 @@ def __test_inline_additional_properties( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['request_body'] = \ request_body return self.call_with_http_info(**kwargs) @@ -1866,7 +1866,7 @@ def __test_json_form_data( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['param'] = \ param kwargs['param2'] = \ @@ -1999,7 +1999,7 @@ def __test_query_parameter_collection_format( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pipe'] = \ pipe kwargs['ioutil'] = \ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py index fa7e0c2dec10..bafdac598b99 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py @@ -110,7 +110,7 @@ def __test_classname( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['client_client'] = \ client_client return self.call_with_http_info(**kwargs) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py index 2a7a458e884a..74fdac9bf401 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -110,7 +110,7 @@ def __add_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_pet'] = \ pet_pet return self.call_with_http_info(**kwargs) @@ -239,7 +239,7 @@ def __delete_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -361,7 +361,7 @@ def __find_pets_by_status( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['status'] = \ status return self.call_with_http_info(**kwargs) @@ -490,7 +490,7 @@ def __find_pets_by_tags( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['tags'] = \ tags return self.call_with_http_info(**kwargs) @@ -612,7 +612,7 @@ def __get_pet_by_id( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -731,7 +731,7 @@ def __update_pet( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_pet'] = \ pet_pet return self.call_with_http_info(**kwargs) @@ -861,7 +861,7 @@ def __update_pet_with_form( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -991,7 +991,7 @@ def __upload_file( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_id'] = \ pet_id return self.call_with_http_info(**kwargs) @@ -1124,7 +1124,7 @@ def __upload_file_with_required_file( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['pet_id'] = \ pet_id kwargs['required_file'] = \ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py index 148b90ecd607..3df42b8e29f8 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -110,7 +110,7 @@ def __delete_order( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['order_id'] = \ order_id return self.call_with_http_info(**kwargs) @@ -222,7 +222,7 @@ def __get_inventory( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.get_inventory = Endpoint( @@ -332,7 +332,7 @@ def __get_order_by_id( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['order_id'] = \ order_id return self.call_with_http_info(**kwargs) @@ -455,7 +455,7 @@ def __place_order( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['order_order'] = \ order_order return self.call_with_http_info(**kwargs) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py index 2c9f2eae8f22..9ab83eb883c7 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py @@ -110,7 +110,7 @@ def __create_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['user_user'] = \ user_user return self.call_with_http_info(**kwargs) @@ -225,7 +225,7 @@ def __create_users_with_array_input( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['user_user'] = \ user_user return self.call_with_http_info(**kwargs) @@ -340,7 +340,7 @@ def __create_users_with_list_input( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['user_user'] = \ user_user return self.call_with_http_info(**kwargs) @@ -456,7 +456,7 @@ def __delete_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['username'] = \ username return self.call_with_http_info(**kwargs) @@ -570,7 +570,7 @@ def __get_user_by_name( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['username'] = \ username return self.call_with_http_info(**kwargs) @@ -689,7 +689,7 @@ def __login_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['username'] = \ username kwargs['password'] = \ @@ -811,7 +811,7 @@ def __logout_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.logout_user = Endpoint( @@ -919,7 +919,7 @@ def __update_user( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', None) + kwargs['_host_index'] = kwargs.get('_host_index') kwargs['username'] = \ username kwargs['user_user'] = \ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py index 3e4a25650fda..0d194e97b92c 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py @@ -171,7 +171,7 @@ def __init__(self, host=None, """ self.server_variables = server_variables or {} self.server_operation_variables = server_operation_variables or {} - """Default sever variables + """Default server variables """ self.temp_folder_path = None """Temp file folder for downloading files @@ -549,6 +549,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value + :param servers: host settings for the endpoint :return: URL based on host settings """ variables = {} if variables is None else variables From 5eec72936750c4afd35b909699705ba54f785e20 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Fri, 5 Jun 2020 15:45:09 +0200 Subject: [PATCH 05/18] Add ParameterizedServer feature to Python experimental --- docs/generators/python-experimental.md | 2 +- .../codegen/languages/PythonClientExperimentalCodegen.java | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/generators/python-experimental.md b/docs/generators/python-experimental.md index 546dcc22542a..57fe34700234 100644 --- a/docs/generators/python-experimental.md +++ b/docs/generators/python-experimental.md @@ -162,7 +162,7 @@ sidebar_label: python-experimental |Examples|✓|OAS2,OAS3 |XMLStructureDefinitions|✗|OAS2,OAS3 |MultiServer|✗|OAS3 -|ParameterizedServer|✗|OAS3 +|ParameterizedServer|✓|OAS3 |ParameterStyling|✗|OAS3 |Callbacks|✗|OAS3 |LinkObjects|✗|OAS3 diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java index e5adf04afdf9..4c13df3c1781 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java @@ -72,6 +72,9 @@ public PythonClientExperimentalCodegen() { SecurityFeature.ApiKey, SecurityFeature.OAuth2_Implicit )) + .includeGlobalFeatures( + GlobalFeature.ParameterizedServer + ) .excludeGlobalFeatures( GlobalFeature.XMLStructureDefinitions, GlobalFeature.Callbacks, From df1c3242d6641b357272912f50c8abaa0ccf60d2 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Fri, 5 Jun 2020 17:23:17 +0200 Subject: [PATCH 06/18] Fix lookup of server variables --- .../resources/python/configuration.mustache | 2 +- .../petstore_api/configuration.py | 2 +- .../petstore_api/configuration.py | 2 +- .../petstore_api/configuration.py | 2 +- .../python/petstore_api/configuration.py | 2 +- .../petstore_api/configuration.py | 2 +- .../python/petstore_api/configuration.py | 35 ++++++++++++++++--- 7 files changed, 36 insertions(+), 11 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python/configuration.mustache b/modules/openapi-generator/src/main/resources/python/configuration.mustache index 8b087a49e0fe..7f3e8a65a3fb 100644 --- a/modules/openapi-generator/src/main/resources/python/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/python/configuration.mustache @@ -591,7 +591,7 @@ conf = {{{packageName}}}.Configuration( url = server['url'] # go through variables and replace placeholders - for variable_name, variable in server['variables'].items(): + for variable_name, variable in server.get('variables', {}).items(): used_value = variables.get( variable_name, variable['default_value']) diff --git a/samples/client/petstore/python-asyncio/petstore_api/configuration.py b/samples/client/petstore/python-asyncio/petstore_api/configuration.py index 08f439a4b683..bc27ca70129f 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/configuration.py +++ b/samples/client/petstore/python-asyncio/petstore_api/configuration.py @@ -462,7 +462,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): url = server['url'] # go through variables and replace placeholders - for variable_name, variable in server['variables'].items(): + for variable_name, variable in server.get('variables', {}).items(): used_value = variables.get( variable_name, variable['default_value']) diff --git a/samples/client/petstore/python-experimental/petstore_api/configuration.py b/samples/client/petstore/python-experimental/petstore_api/configuration.py index 1f03df65feff..bfbfb217a666 100644 --- a/samples/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/client/petstore/python-experimental/petstore_api/configuration.py @@ -466,7 +466,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): url = server['url'] # go through variables and replace placeholders - for variable_name, variable in server['variables'].items(): + for variable_name, variable in server.get('variables', {}).items(): used_value = variables.get( variable_name, variable['default_value']) diff --git a/samples/client/petstore/python-tornado/petstore_api/configuration.py b/samples/client/petstore/python-tornado/petstore_api/configuration.py index 1f03df65feff..bfbfb217a666 100644 --- a/samples/client/petstore/python-tornado/petstore_api/configuration.py +++ b/samples/client/petstore/python-tornado/petstore_api/configuration.py @@ -466,7 +466,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): url = server['url'] # go through variables and replace placeholders - for variable_name, variable in server['variables'].items(): + for variable_name, variable in server.get('variables', {}).items(): used_value = variables.get( variable_name, variable['default_value']) diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index 1f03df65feff..bfbfb217a666 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -466,7 +466,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): url = server['url'] # go through variables and replace placeholders - for variable_name, variable in server['variables'].items(): + for variable_name, variable in server.get('variables', {}).items(): used_value = variables.get( variable_name, variable['default_value']) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py index 0d194e97b92c..6311f3423e0c 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py @@ -565,7 +565,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): url = server['url'] # go through variables and replace placeholders - for variable_name, variable in server['variables'].items(): + for variable_name, variable in server.get('variables', {}).items(): used_value = variables.get( variable_name, variable['default_value']) diff --git a/samples/openapi3/client/petstore/python/petstore_api/configuration.py b/samples/openapi3/client/petstore/python/petstore_api/configuration.py index 850cb907b09f..6311f3423e0c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python/petstore_api/configuration.py @@ -151,18 +151,28 @@ class Configuration(object): _default = None - def __init__(self, host="http://petstore.swagger.io:80/v2", + def __init__(self, host=None, api_key=None, api_key_prefix=None, username=None, password=None, discard_unknown_keys=False, disabled_client_side_validations="", signing_info=None, + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, ): """Constructor """ - self.host = host + self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host """Default Base url """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ self.temp_folder_path = None """Temp file folder for downloading files """ @@ -535,14 +545,15 @@ def get_host_settings(self): } ] - def get_host_from_settings(self, index, variables=None): + def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value + :param servers: host settings for the endpoint :return: URL based on host settings """ variables = {} if variables is None else variables - servers = self.get_host_settings() + servers = self.get_host_settings() if servers is None else servers try: server = servers[index] @@ -554,7 +565,7 @@ def get_host_from_settings(self, index, variables=None): url = server['url'] # go through variables and replace placeholders - for variable_name, variable in server['variables'].items(): + for variable_name, variable in server.get('variables', {}).items(): used_value = variables.get( variable_name, variable['default_value']) @@ -569,3 +580,17 @@ def get_host_from_settings(self, index, variables=None): url = url.replace("{" + variable_name + "}", used_value) return url + + @property + def host(self): + """Return generated host.""" + if self.server_index is None: + return self._base_path + + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None From 39206459fc9c227c2326f548b770d37ba9a7b80c Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Mon, 8 Jun 2020 12:06:05 +0200 Subject: [PATCH 07/18] Add tests and change default value for servers --- .../python/python-experimental/api.mustache | 2 +- .../petstore_api/api/another_fake_api.py | 2 +- .../petstore_api/api/fake_api.py | 30 +++++++++---------- .../api/fake_classname_tags_123_api.py | 2 +- .../petstore_api/api/pet_api.py | 18 +++++------ .../petstore_api/api/store_api.py | 8 ++--- .../petstore_api/api/user_api.py | 16 +++++----- .../petstore_api/api/another_fake_api.py | 2 +- .../petstore_api/api/default_api.py | 2 +- .../petstore_api/api/fake_api.py | 30 +++++++++---------- .../api/fake_classname_tags_123_api.py | 2 +- .../petstore_api/api/pet_api.py | 14 ++++----- .../petstore_api/api/store_api.py | 8 ++--- .../petstore_api/api/user_api.py | 16 +++++----- .../tests/test_api_validation.py | 24 +++++++++++++++ 15 files changed, 100 insertions(+), 76 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache index d05f7af3869a..a4c73bbc497b 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache @@ -190,7 +190,7 @@ class {{classname}}(object): {{/-last}} {{/servers}} {{^servers}} - 'servers': [], + 'servers': None, {{/servers}} }, params_map={ diff --git a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py index 0117dc0c865f..da2b09b09358 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py @@ -122,7 +122,7 @@ def __call_123_test_special_tags( 'endpoint_path': '/another-fake/dummy', 'operation_id': 'call_123_test_special_tags', 'http_method': 'PATCH', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py index 7fa17729e516..0c172a4fd804 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -128,7 +128,7 @@ def __create_xml_item( 'endpoint_path': '/fake/create_xml_item', 'operation_id': 'create_xml_item', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -245,7 +245,7 @@ def __fake_outer_boolean_serialize( 'endpoint_path': '/fake/outer/boolean', 'operation_id': 'fake_outer_boolean_serialize', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -355,7 +355,7 @@ def __fake_outer_composite_serialize( 'endpoint_path': '/fake/outer/composite', 'operation_id': 'fake_outer_composite_serialize', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -465,7 +465,7 @@ def __fake_outer_enum_serialize( 'endpoint_path': '/fake/outer/enum', 'operation_id': 'fake_outer_enum_serialize', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -575,7 +575,7 @@ def __fake_outer_number_serialize( 'endpoint_path': '/fake/outer/number', 'operation_id': 'fake_outer_number_serialize', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -685,7 +685,7 @@ def __fake_outer_string_serialize( 'endpoint_path': '/fake/outer/string', 'operation_id': 'fake_outer_string_serialize', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -799,7 +799,7 @@ def __test_body_with_file_schema( 'endpoint_path': '/fake/body-with-file-schema', 'operation_id': 'test_body_with_file_schema', 'http_method': 'PUT', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -918,7 +918,7 @@ def __test_body_with_query_params( 'endpoint_path': '/fake/body-with-query-params', 'operation_id': 'test_body_with_query_params', 'http_method': 'PUT', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1040,7 +1040,7 @@ def __test_client_model( 'endpoint_path': '/fake', 'operation_id': 'test_client_model', 'http_method': 'PATCH', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1174,7 +1174,7 @@ def __test_endpoint_enums_length_one( 'endpoint_path': '/fake/enums-of-length-one/{path_string}/{path_integer}', 'operation_id': 'test_endpoint_enums_length_one', 'http_method': 'PUT', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1362,7 +1362,7 @@ def __test_endpoint_parameters( 'endpoint_path': '/fake', 'operation_id': 'test_endpoint_parameters', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1599,7 +1599,7 @@ def __test_enum_parameters( 'endpoint_path': '/fake', 'operation_id': 'test_enum_parameters', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1814,7 +1814,7 @@ def __test_group_parameters( 'endpoint_path': '/fake', 'operation_id': 'test_group_parameters', 'http_method': 'DELETE', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1955,7 +1955,7 @@ def __test_inline_additional_properties( 'endpoint_path': '/fake/inline-additionalProperties', 'operation_id': 'test_inline_additional_properties', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -2074,7 +2074,7 @@ def __test_json_form_data( 'endpoint_path': '/fake/jsonFormData', 'operation_id': 'test_json_form_data', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py index c54e632838ed..171258aa767c 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py @@ -124,7 +124,7 @@ def __test_classname( 'endpoint_path': '/fake_classname_test', 'operation_id': 'test_classname', 'http_method': 'PATCH', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py index 2469be4ef084..1bf7bc152049 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -124,7 +124,7 @@ def __add_pet( 'endpoint_path': '/pet', 'operation_id': 'add_pet', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -243,7 +243,7 @@ def __delete_pet( 'endpoint_path': '/pet/{petId}', 'operation_id': 'delete_pet', 'http_method': 'DELETE', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -365,7 +365,7 @@ def __find_pets_by_status( 'endpoint_path': '/pet/findByStatus', 'operation_id': 'find_pets_by_status', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -493,7 +493,7 @@ def __find_pets_by_tags( 'endpoint_path': '/pet/findByTags', 'operation_id': 'find_pets_by_tags', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -614,7 +614,7 @@ def __get_pet_by_id( 'endpoint_path': '/pet/{petId}', 'operation_id': 'get_pet_by_id', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -733,7 +733,7 @@ def __update_pet( 'endpoint_path': '/pet', 'operation_id': 'update_pet', 'http_method': 'PUT', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -853,7 +853,7 @@ def __update_pet_with_form( 'endpoint_path': '/pet/{petId}', 'operation_id': 'update_pet_with_form', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -984,7 +984,7 @@ def __upload_file( 'endpoint_path': '/pet/{petId}/uploadImage', 'operation_id': 'upload_file', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1125,7 +1125,7 @@ def __upload_file_with_required_file( 'endpoint_path': '/fake/{petId}/uploadImageWithRequiredFile', 'operation_id': 'upload_file_with_required_file', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py index b6728a637d29..bf54f43beb03 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -122,7 +122,7 @@ def __delete_order( 'endpoint_path': '/store/order/{order_id}', 'operation_id': 'delete_order', 'http_method': 'DELETE', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -234,7 +234,7 @@ def __get_inventory( 'endpoint_path': '/store/inventory', 'operation_id': 'get_inventory', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -344,7 +344,7 @@ def __get_order_by_id( 'endpoint_path': '/store/order/{order_id}', 'operation_id': 'get_order_by_id', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -467,7 +467,7 @@ def __place_order( 'endpoint_path': '/store/order', 'operation_id': 'place_order', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py index c34fab733969..18012bc4b2a6 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py @@ -122,7 +122,7 @@ def __create_user( 'endpoint_path': '/user', 'operation_id': 'create_user', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -235,7 +235,7 @@ def __create_users_with_array_input( 'endpoint_path': '/user/createWithArray', 'operation_id': 'create_users_with_array_input', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -348,7 +348,7 @@ def __create_users_with_list_input( 'endpoint_path': '/user/createWithList', 'operation_id': 'create_users_with_list_input', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -462,7 +462,7 @@ def __delete_user( 'endpoint_path': '/user/{username}', 'operation_id': 'delete_user', 'http_method': 'DELETE', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -576,7 +576,7 @@ def __get_user_by_name( 'endpoint_path': '/user/{username}', 'operation_id': 'get_user_by_name', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -697,7 +697,7 @@ def __login_user( 'endpoint_path': '/user/login', 'operation_id': 'login_user', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -815,7 +815,7 @@ def __logout_user( 'endpoint_path': '/user/logout', 'operation_id': 'logout_user', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -927,7 +927,7 @@ def __update_user( 'endpoint_path': '/user/{username}', 'operation_id': 'update_user', 'http_method': 'PUT', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py index 5d8d22d67429..adb49522f518 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py @@ -122,7 +122,7 @@ def __call_123_test_special_tags( 'endpoint_path': '/another-fake/dummy', 'operation_id': 'call_123_test_special_tags', 'http_method': 'PATCH', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py index e17584ef244e..eefad367e399 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py @@ -116,7 +116,7 @@ def __foo_get( 'endpoint_path': '/foo', 'operation_id': 'foo_get', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py index 8982177cced4..b61a0f15ee47 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -121,7 +121,7 @@ def __fake_health_get( 'endpoint_path': '/fake/health', 'operation_id': 'fake_health_get', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -227,7 +227,7 @@ def __fake_outer_boolean_serialize( 'endpoint_path': '/fake/outer/boolean', 'operation_id': 'fake_outer_boolean_serialize', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -339,7 +339,7 @@ def __fake_outer_composite_serialize( 'endpoint_path': '/fake/outer/composite', 'operation_id': 'fake_outer_composite_serialize', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -451,7 +451,7 @@ def __fake_outer_number_serialize( 'endpoint_path': '/fake/outer/number', 'operation_id': 'fake_outer_number_serialize', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -563,7 +563,7 @@ def __fake_outer_string_serialize( 'endpoint_path': '/fake/outer/string', 'operation_id': 'fake_outer_string_serialize', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -673,7 +673,7 @@ def __get_array_of_enums( 'endpoint_path': '/fake/array-of-enums', 'operation_id': 'get_array_of_enums', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -783,7 +783,7 @@ def __test_body_with_file_schema( 'endpoint_path': '/fake/body-with-file-schema', 'operation_id': 'test_body_with_file_schema', 'http_method': 'PUT', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -902,7 +902,7 @@ def __test_body_with_query_params( 'endpoint_path': '/fake/body-with-query-params', 'operation_id': 'test_body_with_query_params', 'http_method': 'PUT', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1024,7 +1024,7 @@ def __test_client_model( 'endpoint_path': '/fake', 'operation_id': 'test_client_model', 'http_method': 'PATCH', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1166,7 +1166,7 @@ def __test_endpoint_parameters( 'endpoint_path': '/fake', 'operation_id': 'test_endpoint_parameters', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1403,7 +1403,7 @@ def __test_enum_parameters( 'endpoint_path': '/fake', 'operation_id': 'test_enum_parameters', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1620,7 +1620,7 @@ def __test_group_parameters( 'endpoint_path': '/fake', 'operation_id': 'test_group_parameters', 'http_method': 'DELETE', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1761,7 +1761,7 @@ def __test_inline_additional_properties( 'endpoint_path': '/fake/inline-additionalProperties', 'operation_id': 'test_inline_additional_properties', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1880,7 +1880,7 @@ def __test_json_form_data( 'endpoint_path': '/fake/jsonFormData', 'operation_id': 'test_json_form_data', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -2019,7 +2019,7 @@ def __test_query_parameter_collection_format( 'endpoint_path': '/fake/test-query-paramters', 'operation_id': 'test_query_parameter_collection_format', 'http_method': 'PUT', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py index bafdac598b99..edf41c02564c 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py @@ -124,7 +124,7 @@ def __test_classname( 'endpoint_path': '/fake_classname_test', 'operation_id': 'test_classname', 'http_method': 'PATCH', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py index 74fdac9bf401..6bb4b729f82e 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -253,7 +253,7 @@ def __delete_pet( 'endpoint_path': '/pet/{petId}', 'operation_id': 'delete_pet', 'http_method': 'DELETE', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -376,7 +376,7 @@ def __find_pets_by_status( 'endpoint_path': '/pet/findByStatus', 'operation_id': 'find_pets_by_status', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -505,7 +505,7 @@ def __find_pets_by_tags( 'endpoint_path': '/pet/findByTags', 'operation_id': 'find_pets_by_tags', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -626,7 +626,7 @@ def __get_pet_by_id( 'endpoint_path': '/pet/{petId}', 'operation_id': 'get_pet_by_id', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -875,7 +875,7 @@ def __update_pet_with_form( 'endpoint_path': '/pet/{petId}', 'operation_id': 'update_pet_with_form', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1005,7 +1005,7 @@ def __upload_file( 'endpoint_path': '/pet/{petId}/uploadImage', 'operation_id': 'upload_file', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -1140,7 +1140,7 @@ def __upload_file_with_required_file( 'endpoint_path': '/fake/{petId}/uploadImageWithRequiredFile', 'operation_id': 'upload_file_with_required_file', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py index 3df42b8e29f8..42ecda441504 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -122,7 +122,7 @@ def __delete_order( 'endpoint_path': '/store/order/{order_id}', 'operation_id': 'delete_order', 'http_method': 'DELETE', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -234,7 +234,7 @@ def __get_inventory( 'endpoint_path': '/store/inventory', 'operation_id': 'get_inventory', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -344,7 +344,7 @@ def __get_order_by_id( 'endpoint_path': '/store/order/{order_id}', 'operation_id': 'get_order_by_id', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -467,7 +467,7 @@ def __place_order( 'endpoint_path': '/store/order', 'operation_id': 'place_order', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py index 9ab83eb883c7..8bc33a731134 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py @@ -122,7 +122,7 @@ def __create_user( 'endpoint_path': '/user', 'operation_id': 'create_user', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -237,7 +237,7 @@ def __create_users_with_array_input( 'endpoint_path': '/user/createWithArray', 'operation_id': 'create_users_with_array_input', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -352,7 +352,7 @@ def __create_users_with_list_input( 'endpoint_path': '/user/createWithList', 'operation_id': 'create_users_with_list_input', 'http_method': 'POST', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -468,7 +468,7 @@ def __delete_user( 'endpoint_path': '/user/{username}', 'operation_id': 'delete_user', 'http_method': 'DELETE', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -582,7 +582,7 @@ def __get_user_by_name( 'endpoint_path': '/user/{username}', 'operation_id': 'get_user_by_name', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -703,7 +703,7 @@ def __login_user( 'endpoint_path': '/user/login', 'operation_id': 'login_user', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -821,7 +821,7 @@ def __logout_user( 'endpoint_path': '/user/logout', 'operation_id': 'logout_user', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -933,7 +933,7 @@ def __update_user( 'endpoint_path': '/user/{username}', 'operation_id': 'update_user', 'http_method': 'PUT', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/openapi3/client/petstore/python-experimental/tests/test_api_validation.py b/samples/openapi3/client/petstore/python-experimental/tests/test_api_validation.py index e9eb0a70f786..35de4c265115 100644 --- a/samples/openapi3/client/petstore/python-experimental/tests/test_api_validation.py +++ b/samples/openapi3/client/petstore/python-experimental/tests/test_api_validation.py @@ -13,6 +13,7 @@ import time import atexit import datetime +import functools import json import sys import weakref @@ -21,6 +22,7 @@ from collections import namedtuple import petstore_api +from petstore_api.api import pet_api from petstore_api.model import array_of_enums from petstore_api.model import format_test from petstore_api.model import outer_enum @@ -44,6 +46,28 @@ def test_configuration(self): config.disabled_client_side_validations = 'foo' config.disabled_client_side_validations = "" + def test_servers(self): + config = petstore_api.Configuration(server_index=1, server_variables={'version': 'v1'}) + api_client = petstore_api.ApiClient(config) + api = pet_api.PetApi(api_client) + + def request(expected_url, method, url, **kwargs): + assert expected_url == url + raise RuntimeError('pass') + + api_client.request = functools.partial(request, 'http://path-server-test.petstore.local/v2/pet') + try: + api.add_pet({'name': 'pet', 'photo_urls': []}) + except RuntimeError as e: + assert "pass" == str(e) + + api_client.request = functools.partial(request, 'http://path-server-test.petstore.local/v2/pet') + try: + api.delete_pet({'id': 'xxx'}) + except RuntimeError as e: + assert "pass" == str(e) + + def test_array_of_enums(self): data = [ "placed", None From 7420edb6ccf308d350d5601e626fb7e68a16976f Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Mon, 8 Jun 2020 12:15:06 +0200 Subject: [PATCH 08/18] Fix server variables --- .../main/resources/python/python-experimental/api.mustache | 2 +- .../python-experimental/petstore_api/api/another_fake_api.py | 2 +- .../python-experimental/petstore_api/api/fake_api.py | 2 +- .../petstore_api/api/fake_classname_tags_123_api.py | 2 +- .../petstore/python-experimental/petstore_api/api/pet_api.py | 2 +- .../python-experimental/petstore_api/api/store_api.py | 2 +- .../python-experimental/petstore_api/api/user_api.py | 2 +- .../python-experimental/petstore_api/api/another_fake_api.py | 2 +- .../python-experimental/petstore_api/api/default_api.py | 2 +- .../python-experimental/petstore_api/api/fake_api.py | 2 +- .../petstore_api/api/fake_classname_tags_123_api.py | 2 +- .../petstore/python-experimental/petstore_api/api/pet_api.py | 2 +- .../python-experimental/petstore_api/api/store_api.py | 2 +- .../python-experimental/petstore_api/api/user_api.py | 2 +- .../python-experimental/tests/test_api_validation.py | 5 ++--- 15 files changed, 16 insertions(+), 17 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache index a4c73bbc497b..8f75af5f99b0 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache @@ -475,7 +475,7 @@ class Endpoint(object): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py index da2b09b09358..0fc2c6207500 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py @@ -324,7 +324,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py index 0c172a4fd804..5301ad82fc1c 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -2281,7 +2281,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py index 171258aa767c..81f3d17cccfb 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py @@ -326,7 +326,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py index 1bf7bc152049..85a3fb92d8dc 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -1339,7 +1339,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py index bf54f43beb03..0c08c676444f 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -668,7 +668,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py index 18012bc4b2a6..bf5b6ed03c2f 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py @@ -1131,7 +1131,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py index adb49522f518..7ccea5f1282c 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py @@ -324,7 +324,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py index eefad367e399..3f63b21f61e1 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py @@ -310,7 +310,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py index b61a0f15ee47..0037835874ff 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -2247,7 +2247,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py index edf41c02564c..63ad620b5894 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py @@ -326,7 +326,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py index 6bb4b729f82e..2c1c95561aeb 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -1354,7 +1354,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py index 42ecda441504..20e7314fd09f 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -670,7 +670,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py index 8bc33a731134..c51936849465 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py @@ -1139,7 +1139,7 @@ def call_with_http_info(self, **kwargs): self.settings['operation_id'], self.api_client.configuration.server_index ) if kwargs['_host_index'] is None else kwargs['_host_index'] server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'] + self.settings['operation_id'], self.api_client.configuration.server_variables ) _host = self.api_client.configuration.get_host_from_settings( index, variables=server_variables, servers=self.settings['servers'] diff --git a/samples/openapi3/client/petstore/python-experimental/tests/test_api_validation.py b/samples/openapi3/client/petstore/python-experimental/tests/test_api_validation.py index 35de4c265115..ced6a6c23186 100644 --- a/samples/openapi3/client/petstore/python-experimental/tests/test_api_validation.py +++ b/samples/openapi3/client/petstore/python-experimental/tests/test_api_validation.py @@ -61,13 +61,12 @@ def request(expected_url, method, url, **kwargs): except RuntimeError as e: assert "pass" == str(e) - api_client.request = functools.partial(request, 'http://path-server-test.petstore.local/v2/pet') + api_client.request = functools.partial(request, 'https://localhost:8080/v1/pet/123456789') try: - api.delete_pet({'id': 'xxx'}) + api.delete_pet(123456789) except RuntimeError as e: assert "pass" == str(e) - def test_array_of_enums(self): data = [ "placed", None From 5422cfd66af43372998367b94758dfba8c00d972 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Mon, 8 Jun 2020 13:50:44 +0200 Subject: [PATCH 09/18] Return base path when index is None --- .../src/main/resources/python/configuration.mustache | 3 +++ .../petstore/python-asyncio/petstore_api/configuration.py | 3 +++ .../petstore/python-experimental/petstore_api/configuration.py | 3 +++ .../client/petstore/python-experimental/test/test_fake_api.py | 2 +- .../petstore/python-tornado/petstore_api/configuration.py | 3 +++ samples/client/petstore/python/petstore_api/configuration.py | 3 +++ .../petstore/python-experimental/petstore_api/configuration.py | 3 +++ 7 files changed, 19 insertions(+), 1 deletion(-) diff --git a/modules/openapi-generator/src/main/resources/python/configuration.mustache b/modules/openapi-generator/src/main/resources/python/configuration.mustache index 7f3e8a65a3fb..19e1a4e5ac8e 100644 --- a/modules/openapi-generator/src/main/resources/python/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/python/configuration.mustache @@ -578,6 +578,9 @@ conf = {{{packageName}}}.Configuration( :param servers: host settings for the endpoint :return: URL based on host settings """ + if index is None: + return self._base_path + variables = {} if variables is None else variables servers = self.get_host_settings() if servers is None else servers diff --git a/samples/client/petstore/python-asyncio/petstore_api/configuration.py b/samples/client/petstore/python-asyncio/petstore_api/configuration.py index bc27ca70129f..59de25ed168b 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/configuration.py +++ b/samples/client/petstore/python-asyncio/petstore_api/configuration.py @@ -449,6 +449,9 @@ def get_host_from_settings(self, index, variables=None, servers=None): :param servers: host settings for the endpoint :return: URL based on host settings """ + if index is None: + return self._base_path + variables = {} if variables is None else variables servers = self.get_host_settings() if servers is None else servers diff --git a/samples/client/petstore/python-experimental/petstore_api/configuration.py b/samples/client/petstore/python-experimental/petstore_api/configuration.py index bfbfb217a666..c6fa6ed0a438 100644 --- a/samples/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/client/petstore/python-experimental/petstore_api/configuration.py @@ -453,6 +453,9 @@ def get_host_from_settings(self, index, variables=None, servers=None): :param servers: host settings for the endpoint :return: URL based on host settings """ + if index is None: + return self._base_path + variables = {} if variables is None else variables servers = self.get_host_settings() if servers is None else servers diff --git a/samples/client/petstore/python-experimental/test/test_fake_api.py b/samples/client/petstore/python-experimental/test/test_fake_api.py index d55e538b8608..8c49c709ef5e 100644 --- a/samples/client/petstore/python-experimental/test/test_fake_api.py +++ b/samples/client/petstore/python-experimental/test/test_fake_api.py @@ -107,7 +107,7 @@ def test_test_endpoint_enums_length_one(self): call_with_http_info.assert_called_with( _check_input_type=True, _check_return_type=True, - _host_index=0, + _host_index=None, _preload_content=True, _request_timeout=None, _return_http_data_only=True, diff --git a/samples/client/petstore/python-tornado/petstore_api/configuration.py b/samples/client/petstore/python-tornado/petstore_api/configuration.py index bfbfb217a666..c6fa6ed0a438 100644 --- a/samples/client/petstore/python-tornado/petstore_api/configuration.py +++ b/samples/client/petstore/python-tornado/petstore_api/configuration.py @@ -453,6 +453,9 @@ def get_host_from_settings(self, index, variables=None, servers=None): :param servers: host settings for the endpoint :return: URL based on host settings """ + if index is None: + return self._base_path + variables = {} if variables is None else variables servers = self.get_host_settings() if servers is None else servers diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index bfbfb217a666..c6fa6ed0a438 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -453,6 +453,9 @@ def get_host_from_settings(self, index, variables=None, servers=None): :param servers: host settings for the endpoint :return: URL based on host settings """ + if index is None: + return self._base_path + variables = {} if variables is None else variables servers = self.get_host_settings() if servers is None else servers diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py index 6311f3423e0c..e980dd739bc9 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py @@ -552,6 +552,9 @@ def get_host_from_settings(self, index, variables=None, servers=None): :param servers: host settings for the endpoint :return: URL based on host settings """ + if index is None: + return self._base_path + variables = {} if variables is None else variables servers = self.get_host_settings() if servers is None else servers From 294d164ab033df0f7c60f38885c9b57c1fb711c3 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Mon, 8 Jun 2020 17:15:06 +0200 Subject: [PATCH 10/18] Use HOST --- .../python-experimental/tests/test_http_signature.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/openapi3/client/petstore/python-experimental/tests/test_http_signature.py b/samples/openapi3/client/petstore/python-experimental/tests/test_http_signature.py index e8f0dd186a98..2e3227f70d4f 100644 --- a/samples/openapi3/client/petstore/python-experimental/tests/test_http_signature.py +++ b/samples/openapi3/client/petstore/python-experimental/tests/test_http_signature.py @@ -294,7 +294,7 @@ def test_valid_http_signature(self): api_client.rest_client.pool_manager = mock_pool mock_pool.set_signing_config(signing_cfg) - mock_pool.expect_request('POST', 'http://petstore.swagger.io/v2/pet', + mock_pool.expect_request('POST', HOST + '/pet', body=json.dumps(api_client.sanitize_for_serialization(self.pet)), headers={'Content-Type': r'application/json', 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' @@ -325,7 +325,7 @@ def test_valid_http_signature_with_defaults(self): api_client.rest_client.pool_manager = mock_pool mock_pool.set_signing_config(signing_cfg) - mock_pool.expect_request('POST', 'http://petstore.swagger.io/v2/pet', + mock_pool.expect_request('POST', HOST + '/pet', body=json.dumps(api_client.sanitize_for_serialization(self.pet)), headers={'Content-Type': r'application/json', 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' @@ -361,7 +361,7 @@ def test_valid_http_signature_rsassa_pkcs1v15(self): api_client.rest_client.pool_manager = mock_pool mock_pool.set_signing_config(signing_cfg) - mock_pool.expect_request('POST', 'http://petstore.swagger.io/v2/pet', + mock_pool.expect_request('POST', HOST + '/pet', body=json.dumps(api_client.sanitize_for_serialization(self.pet)), headers={'Content-Type': r'application/json', 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' @@ -397,7 +397,7 @@ def test_valid_http_signature_rsassa_pss(self): api_client.rest_client.pool_manager = mock_pool mock_pool.set_signing_config(signing_cfg) - mock_pool.expect_request('POST', 'http://petstore.swagger.io/v2/pet', + mock_pool.expect_request('POST', HOST + '/pet', body=json.dumps(api_client.sanitize_for_serialization(self.pet)), headers={'Content-Type': r'application/json', 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' @@ -433,7 +433,7 @@ def test_valid_http_signature_ec_p521(self): api_client.rest_client.pool_manager = mock_pool mock_pool.set_signing_config(signing_cfg) - mock_pool.expect_request('POST', 'http://petstore.swagger.io/v2/pet', + mock_pool.expect_request('POST', HOST + '/pet', body=json.dumps(api_client.sanitize_for_serialization(self.pet)), headers={'Content-Type': r'application/json', 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' From f38fc72f8343345bcf751f245a7bac661c57dd2c Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Thu, 11 Jun 2020 16:35:17 +0200 Subject: [PATCH 11/18] Apply suggestions from code review --- .../src/main/resources/python/configuration.mustache | 3 --- .../src/main/resources/python/python-experimental/api.mustache | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python/configuration.mustache b/modules/openapi-generator/src/main/resources/python/configuration.mustache index 19e1a4e5ac8e..5ddb0d6a6aa4 100644 --- a/modules/openapi-generator/src/main/resources/python/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/python/configuration.mustache @@ -613,9 +613,6 @@ conf = {{{packageName}}}.Configuration( @property def host(self): """Return generated host.""" - if self.server_index is None: - return self._base_path - return self.get_host_from_settings(self.server_index, variables=self.server_variables) @host.setter diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache index 8f75af5f99b0..7a0fb8e519a7 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/api.mustache @@ -103,7 +103,7 @@ class {{classname}}(object): _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously From 8ec2cb7f7fb227e373936b816ba4ed67e92be624 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Thu, 11 Jun 2020 16:58:57 +0200 Subject: [PATCH 12/18] Apply suggestions from code review --- .../src/main/resources/python/configuration.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/openapi-generator/src/main/resources/python/configuration.mustache b/modules/openapi-generator/src/main/resources/python/configuration.mustache index 5ddb0d6a6aa4..bf9f8f6bad77 100644 --- a/modules/openapi-generator/src/main/resources/python/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/python/configuration.mustache @@ -575,7 +575,7 @@ conf = {{{packageName}}}.Configuration( """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value - :param servers: host settings for the endpoint + :param servers: an array of host settings or None :return: URL based on host settings """ if index is None: From 6e973605c39bcbc06b73874b961f3e4f18e0fe20 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Thu, 11 Jun 2020 17:34:41 +0200 Subject: [PATCH 13/18] regenerated --- .../petstore_api/configuration.py | 5 +--- .../petstore_api/api/another_fake_api.py | 2 +- .../petstore_api/api/fake_api.py | 30 +++++++++---------- .../api/fake_classname_tags_123_api.py | 2 +- .../petstore_api/api/pet_api.py | 18 +++++------ .../petstore_api/api/store_api.py | 8 ++--- .../petstore_api/api/user_api.py | 16 +++++----- .../petstore_api/configuration.py | 5 +--- .../petstore_api/configuration.py | 5 +--- .../python/petstore_api/configuration.py | 5 +--- .../petstore_api/api/another_fake_api.py | 2 +- .../petstore_api/api/default_api.py | 2 +- .../petstore_api/api/fake_api.py | 30 +++++++++---------- .../api/fake_classname_tags_123_api.py | 2 +- .../petstore_api/api/pet_api.py | 18 +++++------ .../petstore_api/api/store_api.py | 8 ++--- .../petstore_api/api/user_api.py | 16 +++++----- .../petstore_api/configuration.py | 5 +--- 18 files changed, 82 insertions(+), 97 deletions(-) diff --git a/samples/client/petstore/python-asyncio/petstore_api/configuration.py b/samples/client/petstore/python-asyncio/petstore_api/configuration.py index 59de25ed168b..084743293dcb 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/configuration.py +++ b/samples/client/petstore/python-asyncio/petstore_api/configuration.py @@ -446,7 +446,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value - :param servers: host settings for the endpoint + :param servers: an array of host settings or None :return: URL based on host settings """ if index is None: @@ -484,9 +484,6 @@ def get_host_from_settings(self, index, variables=None, servers=None): @property def host(self): """Return generated host.""" - if self.server_index is None: - return self._base_path - return self.get_host_from_settings(self.server_index, variables=self.server_variables) @host.setter diff --git a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py index 0fc2c6207500..6860231f94a3 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/another_fake_api.py @@ -82,7 +82,7 @@ def __call_123_test_special_tags( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py index 5301ad82fc1c..113eae92697b 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -88,7 +88,7 @@ def __create_xml_item( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -207,7 +207,7 @@ def __fake_outer_boolean_serialize( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -317,7 +317,7 @@ def __fake_outer_composite_serialize( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -427,7 +427,7 @@ def __fake_outer_enum_serialize( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -537,7 +537,7 @@ def __fake_outer_number_serialize( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -647,7 +647,7 @@ def __fake_outer_string_serialize( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -759,7 +759,7 @@ def __test_body_with_file_schema( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -876,7 +876,7 @@ def __test_body_with_query_params( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1000,7 +1000,7 @@ def __test_client_model( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1126,7 +1126,7 @@ def __test_endpoint_enums_length_one( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1314,7 +1314,7 @@ def __test_endpoint_parameters( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1561,7 +1561,7 @@ def __test_enum_parameters( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1770,7 +1770,7 @@ def __test_group_parameters( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1915,7 +1915,7 @@ def __test_inline_additional_properties( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -2032,7 +2032,7 @@ def __test_json_form_data( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py index 81f3d17cccfb..f1c8560557c8 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py @@ -82,7 +82,7 @@ def __test_classname( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py index 85a3fb92d8dc..aa4522f985ad 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -82,7 +82,7 @@ def __add_pet( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -201,7 +201,7 @@ def __delete_pet( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -323,7 +323,7 @@ def __find_pets_by_status( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -451,7 +451,7 @@ def __find_pets_by_tags( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -572,7 +572,7 @@ def __get_pet_by_id( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -691,7 +691,7 @@ def __update_pet( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -811,7 +811,7 @@ def __update_pet_with_form( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -942,7 +942,7 @@ def __upload_file( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1081,7 +1081,7 @@ def __upload_file_with_required_file( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py index 0c08c676444f..48162d0fbfd5 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/store_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -82,7 +82,7 @@ def __delete_order( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -194,7 +194,7 @@ def __get_inventory( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -304,7 +304,7 @@ def __get_order_by_id( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -427,7 +427,7 @@ def __place_order( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py index bf5b6ed03c2f..2895e86fb67b 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api/user_api.py +++ b/samples/client/petstore/python-experimental/petstore_api/api/user_api.py @@ -82,7 +82,7 @@ def __create_user( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -195,7 +195,7 @@ def __create_users_with_array_input( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -308,7 +308,7 @@ def __create_users_with_list_input( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -422,7 +422,7 @@ def __delete_user( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -536,7 +536,7 @@ def __get_user_by_name( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -655,7 +655,7 @@ def __login_user( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -777,7 +777,7 @@ def __logout_user( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -885,7 +885,7 @@ def __update_user( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/client/petstore/python-experimental/petstore_api/configuration.py b/samples/client/petstore/python-experimental/petstore_api/configuration.py index c6fa6ed0a438..3c5272a5967b 100644 --- a/samples/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/client/petstore/python-experimental/petstore_api/configuration.py @@ -450,7 +450,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value - :param servers: host settings for the endpoint + :param servers: an array of host settings or None :return: URL based on host settings """ if index is None: @@ -488,9 +488,6 @@ def get_host_from_settings(self, index, variables=None, servers=None): @property def host(self): """Return generated host.""" - if self.server_index is None: - return self._base_path - return self.get_host_from_settings(self.server_index, variables=self.server_variables) @host.setter diff --git a/samples/client/petstore/python-tornado/petstore_api/configuration.py b/samples/client/petstore/python-tornado/petstore_api/configuration.py index c6fa6ed0a438..3c5272a5967b 100644 --- a/samples/client/petstore/python-tornado/petstore_api/configuration.py +++ b/samples/client/petstore/python-tornado/petstore_api/configuration.py @@ -450,7 +450,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value - :param servers: host settings for the endpoint + :param servers: an array of host settings or None :return: URL based on host settings """ if index is None: @@ -488,9 +488,6 @@ def get_host_from_settings(self, index, variables=None, servers=None): @property def host(self): """Return generated host.""" - if self.server_index is None: - return self._base_path - return self.get_host_from_settings(self.server_index, variables=self.server_variables) @host.setter diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index c6fa6ed0a438..3c5272a5967b 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -450,7 +450,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value - :param servers: host settings for the endpoint + :param servers: an array of host settings or None :return: URL based on host settings """ if index is None: @@ -488,9 +488,6 @@ def get_host_from_settings(self, index, variables=None, servers=None): @property def host(self): """Return generated host.""" - if self.server_index is None: - return self._base_path - return self.get_host_from_settings(self.server_index, variables=self.server_variables) @host.setter diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py index 7ccea5f1282c..ba4c5201d751 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py @@ -82,7 +82,7 @@ def __call_123_test_special_tags( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py index 3f63b21f61e1..c51cbe471c62 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py @@ -78,7 +78,7 @@ def __foo_get( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py index c880712d1c8f..1c96278f9772 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -83,7 +83,7 @@ def __fake_health_get( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -189,7 +189,7 @@ def __fake_outer_boolean_serialize( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -301,7 +301,7 @@ def __fake_outer_composite_serialize( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -413,7 +413,7 @@ def __fake_outer_number_serialize( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -525,7 +525,7 @@ def __fake_outer_string_serialize( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -635,7 +635,7 @@ def __get_array_of_enums( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -743,7 +743,7 @@ def __test_body_with_file_schema( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -860,7 +860,7 @@ def __test_body_with_query_params( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -984,7 +984,7 @@ def __test_client_model( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1118,7 +1118,7 @@ def __test_endpoint_parameters( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1365,7 +1365,7 @@ def __test_enum_parameters( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1574,7 +1574,7 @@ def __test_group_parameters( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1721,7 +1721,7 @@ def __test_inline_additional_properties( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1838,7 +1838,7 @@ def __test_json_form_data( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1971,7 +1971,7 @@ def __test_query_parameter_collection_format( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py index 63ad620b5894..1f9276772a2a 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py @@ -82,7 +82,7 @@ def __test_classname( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py index 2c1c95561aeb..097c5874aa9b 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -82,7 +82,7 @@ def __add_pet( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -211,7 +211,7 @@ def __delete_pet( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -333,7 +333,7 @@ def __find_pets_by_status( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -462,7 +462,7 @@ def __find_pets_by_tags( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -584,7 +584,7 @@ def __get_pet_by_id( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -703,7 +703,7 @@ def __update_pet( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -833,7 +833,7 @@ def __update_pet_with_form( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -963,7 +963,7 @@ def __upload_file( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -1096,7 +1096,7 @@ def __upload_file_with_required_file( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py index 20e7314fd09f..7b2774c53779 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -82,7 +82,7 @@ def __delete_order( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -194,7 +194,7 @@ def __get_inventory( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -304,7 +304,7 @@ def __get_order_by_id( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -427,7 +427,7 @@ def __place_order( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py index c51936849465..c53434779f14 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py @@ -82,7 +82,7 @@ def __create_user( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -197,7 +197,7 @@ def __create_users_with_array_input( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -312,7 +312,7 @@ def __create_users_with_list_input( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -428,7 +428,7 @@ def __delete_user( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -542,7 +542,7 @@ def __get_user_by_name( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -661,7 +661,7 @@ def __login_user( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -783,7 +783,7 @@ def __logout_user( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously @@ -891,7 +891,7 @@ def __update_user( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py index e980dd739bc9..1d744ef92131 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py @@ -549,7 +549,7 @@ def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value - :param servers: host settings for the endpoint + :param servers: an array of host settings or None :return: URL based on host settings """ if index is None: @@ -587,9 +587,6 @@ def get_host_from_settings(self, index, variables=None, servers=None): @property def host(self): """Return generated host.""" - if self.server_index is None: - return self._base_path - return self.get_host_from_settings(self.server_index, variables=self.server_variables) @host.setter From 0a57b4cd84d4ecbb4c5477bc530e1a96dfb7f267 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Fri, 12 Jun 2020 11:06:04 +0200 Subject: [PATCH 14/18] Add specific tests for dynamic servers --- ...experimental-features-dynamic-servers.yaml | 6 + .../3_0/features/dynamic-servers.yaml | 92 + .../python-experimental/.gitignore | 66 + .../python-experimental/.gitlab-ci.yml | 33 + .../.openapi-generator-ignore | 23 + .../.openapi-generator/FILES | 25 + .../.openapi-generator/VERSION | 1 + .../python-experimental/.travis.yml | 17 + .../python-experimental/README.md | 116 ++ .../python-experimental/docs/UsageApi.md | 128 ++ .../dynamic_servers/__init__.py | 31 + .../dynamic_servers/api/__init__.py | 6 + .../dynamic_servers/api/usage_api.py | 536 +++++ .../dynamic_servers/api_client.py | 578 ++++++ .../dynamic_servers/apis/__init__.py | 18 + .../dynamic_servers/configuration.py | 464 +++++ .../dynamic_servers/exceptions.py | 139 ++ .../dynamic_servers/model/__init__.py | 5 + .../dynamic_servers/model_utils.py | 1770 +++++++++++++++++ .../dynamic_servers/models/__init__.py | 13 + .../dynamic_servers/rest.py | 291 +++ .../python-experimental/git_push.sh | 58 + .../python-experimental/requirements.txt | 7 + .../python-experimental/setup.cfg | 2 + .../python-experimental/setup.py | 49 + .../python-experimental/test-requirements.txt | 4 + .../python-experimental/test/__init__.py | 0 .../test/test_usage_api.py | 123 ++ .../python-experimental/tox.ini | 9 + 29 files changed, 4610 insertions(+) create mode 100644 bin/configs/python-experimental-features-dynamic-servers.yaml create mode 100644 modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/.gitignore create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/.gitlab-ci.yml create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator-ignore create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/FILES create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/VERSION create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/.travis.yml create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/README.md create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/docs/UsageApi.md create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/__init__.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api/__init__.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api/usage_api.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api_client.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/apis/__init__.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/exceptions.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/model/__init__.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/model_utils.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/models/__init__.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/rest.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/git_push.sh create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/requirements.txt create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/setup.cfg create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/setup.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/test-requirements.txt create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/test/__init__.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/test/test_usage_api.py create mode 100644 samples/openapi3/client/features/dynamic-servers/python-experimental/tox.ini diff --git a/bin/configs/python-experimental-features-dynamic-servers.yaml b/bin/configs/python-experimental-features-dynamic-servers.yaml new file mode 100644 index 000000000000..da52feaf928f --- /dev/null +++ b/bin/configs/python-experimental-features-dynamic-servers.yaml @@ -0,0 +1,6 @@ +generatorName: python-experimental +outputDir: samples/openapi3/client/features/dynamic-servers/python-experimental/ +inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml +templateDir: modules/openapi-generator/src/main/resources/python +additionalProperties: + packageName: dynamic_servers diff --git a/modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml b/modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml new file mode 100644 index 000000000000..4e5ccde6d3ee --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml @@ -0,0 +1,92 @@ +openapi: 3.0.0 +info: + description: This specification shows how to use dynamic servers. + version: 1.0.0 + title: OpenAPI Extension with dynamic servers + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: usage + description: Show usage of dynamic servers +servers: + - url: 'http://{server}.swagger.io:{port}/v2' + description: petstore server + variables: + server: + enum: + - 'petstore' + - 'qa-petstore' + - 'dev-petstore' + default: 'petstore' + port: + enum: + - '80' + - '8080' + default: '80' + - url: https://localhost:8080/{version} + description: The local server + variables: + version: + enum: + - 'v1' + - 'v2' + - 'v3' + default: 'v1' +paths: + /default: + get: + tags: + - usage + summary: Use default server + description: Use default server + operationId: defaultServer + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + /custom: + get: + tags: + - usage + servers: + - url: https://{server}.swagger.io:{port}/v2 + variables: + server: + enum: + - 'custom-petstore' + - 'custom-qa-petstore' + - 'custom-dev-petstore' + default: 'custom-petstore' + port: + enum: + - '80' + - '8080' + default: '8080' + - url: https://localhost:8081/{version} + description: The local custom server + variables: + version: + enum: + - 'v1' + - 'v2' + - 'v3' + default: 'v2' + - url: https://third.example.com/{prefix} + description: The local custom server + variables: + prefix: + default: 'custom' + summary: Use custom server + description: Use custom server + operationId: customServer + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/.gitignore b/samples/openapi3/client/features/dynamic-servers/python-experimental/.gitignore new file mode 100644 index 000000000000..43995bd42fa2 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/.gitignore @@ -0,0 +1,66 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +venv/ +.venv/ +.python-version +.pytest_cache + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/.gitlab-ci.yml b/samples/openapi3/client/features/dynamic-servers/python-experimental/.gitlab-ci.yml new file mode 100644 index 000000000000..b242dc37516c --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/.gitlab-ci.yml @@ -0,0 +1,33 @@ +# ref: https://docs.gitlab.com/ee/ci/README.html + +stages: + - test + +.nosetest: + stage: test + script: + - pip install -r requirements.txt + - pip install -r test-requirements.txt + - pytest --cov=dynamic_servers + +nosetest-2.7: + extends: .nosetest + image: python:2.7-alpine +nosetest-3.3: + extends: .nosetest + image: python:3.3-alpine +nosetest-3.4: + extends: .nosetest + image: python:3.4-alpine +nosetest-3.5: + extends: .nosetest + image: python:3.5-alpine +nosetest-3.6: + extends: .nosetest + image: python:3.6-alpine +nosetest-3.7: + extends: .nosetest + image: python:3.7-alpine +nosetest-3.8: + extends: .nosetest + image: python:3.8-alpine diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator-ignore b/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/FILES b/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/FILES new file mode 100644 index 000000000000..16d0dedd8a10 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/FILES @@ -0,0 +1,25 @@ +.gitignore +.gitlab-ci.yml +.openapi-generator-ignore +.travis.yml +README.md +docs/UsageApi.md +dynamic_servers/__init__.py +dynamic_servers/api/__init__.py +dynamic_servers/api/usage_api.py +dynamic_servers/api_client.py +dynamic_servers/apis/__init__.py +dynamic_servers/configuration.py +dynamic_servers/exceptions.py +dynamic_servers/model/__init__.py +dynamic_servers/model_utils.py +dynamic_servers/models/__init__.py +dynamic_servers/rest.py +git_push.sh +requirements.txt +setup.cfg +setup.py +test-requirements.txt +test/__init__.py +test/test_usage_api.py +tox.ini diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/VERSION b/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/VERSION new file mode 100644 index 000000000000..d99e7162d01f --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/.travis.yml b/samples/openapi3/client/features/dynamic-servers/python-experimental/.travis.yml new file mode 100644 index 000000000000..e6f2ea657f76 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/.travis.yml @@ -0,0 +1,17 @@ +# ref: https://docs.travis-ci.com/user/languages/python +language: python +python: + - "2.7" + - "3.2" + - "3.3" + - "3.4" + - "3.5" + - "3.6" + - "3.7" + - "3.8" +# command to install dependencies +install: + - "pip install -r requirements.txt" + - "pip install -r test-requirements.txt" +# command to run tests +script: pytest --cov=dynamic_servers diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/README.md b/samples/openapi3/client/features/dynamic-servers/python-experimental/README.md new file mode 100644 index 000000000000..81db8a329f8f --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/README.md @@ -0,0 +1,116 @@ +# dynamic-servers +This specification shows how to use dynamic servers. + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PythonClientExperimentalCodegen + +## Requirements. + +Python 2.7 and 3.4+ + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) + +Then import the package: +```python +import dynamic_servers +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import dynamic_servers +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```python +from __future__ import print_function + +import time +import dynamic_servers +from pprint import pprint +from dynamic_servers.api import usage_api +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = dynamic_servers.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + + +# Enter a context with an instance of the API client +with dynamic_servers.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = usage_api.UsageApi(api_client) + + try: + # Use custom server + api_response = api_instance.custom_server() + pprint(api_response) + except dynamic_servers.ApiException as e: + print("Exception when calling UsageApi->custom_server: %s\n" % e) +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*UsageApi* | [**custom_server**](docs/UsageApi.md#custom_server) | **GET** /custom | Use custom server +*UsageApi* | [**default_server**](docs/UsageApi.md#default_server) | **GET** /default | Use default server + + +## Documentation For Models + + + +## Documentation For Authorization + + All endpoints do not require authorization. + +## Author + + + + +## Notes for Large OpenAPI documents +If the OpenAPI document is large, imports in dynamic_servers.apis and dynamic_servers.models may fail with a +RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: + +Solution 1: +Use specific imports for apis and models like: +- `from dynamic_servers.api.default_api import DefaultApi` +- `from dynamic_servers.model.pet import Pet` + +Solution 1: +Before importing the package, adjust the maximum recursion limit as shown below: +``` +import sys +sys.setrecursionlimit(1500) +import dynamic_servers +from dynamic_servers.apis import * +from dynamic_servers.models import * +``` + diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/docs/UsageApi.md b/samples/openapi3/client/features/dynamic-servers/python-experimental/docs/UsageApi.md new file mode 100644 index 000000000000..3c4ed134c538 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/docs/UsageApi.md @@ -0,0 +1,128 @@ +# dynamic_servers.UsageApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**custom_server**](UsageApi.md#custom_server) | **GET** /custom | Use custom server +[**default_server**](UsageApi.md#default_server) | **GET** /default | Use default server + + +# **custom_server** +> {str: (bool, date, datetime, dict, float, int, list, str, none_type)} custom_server() + +Use custom server + +Use custom server + +### Example + +```python +from __future__ import print_function +import time +import dynamic_servers +from dynamic_servers.api import usage_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = dynamic_servers.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with dynamic_servers.ApiClient() as api_client: + # Create an instance of the API class + api_instance = usage_api.UsageApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + # Use custom server + api_response = api_instance.custom_server() + pprint(api_response) + except dynamic_servers.ApiException as e: + print("Exception when calling UsageApi->custom_server: %s\n" % e) +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**{str: (bool, date, datetime, dict, float, int, list, str, none_type)}** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **default_server** +> {str: (bool, date, datetime, dict, float, int, list, str, none_type)} default_server() + +Use default server + +Use default server + +### Example + +```python +from __future__ import print_function +import time +import dynamic_servers +from dynamic_servers.api import usage_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = dynamic_servers.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with dynamic_servers.ApiClient() as api_client: + # Create an instance of the API class + api_instance = usage_api.UsageApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + # Use default server + api_response = api_instance.default_server() + pprint(api_response) + except dynamic_servers.ApiException as e: + print("Exception when calling UsageApi->default_server: %s\n" % e) +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**{str: (bool, date, datetime, dict, float, int, list, str, none_type)}** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/__init__.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/__init__.py new file mode 100644 index 000000000000..e42afd4939e5 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/__init__.py @@ -0,0 +1,31 @@ +# coding: utf-8 + +# flake8: noqa + +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +__version__ = "1.0.0" + +# import ApiClient +from dynamic_servers.api_client import ApiClient + +# import Configuration +from dynamic_servers.configuration import Configuration + +# import exceptions +from dynamic_servers.exceptions import OpenApiException +from dynamic_servers.exceptions import ApiAttributeError +from dynamic_servers.exceptions import ApiTypeError +from dynamic_servers.exceptions import ApiValueError +from dynamic_servers.exceptions import ApiKeyError +from dynamic_servers.exceptions import ApiException \ No newline at end of file diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api/__init__.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api/__init__.py new file mode 100644 index 000000000000..e4e46e3843e0 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api/__init__.py @@ -0,0 +1,6 @@ +from __future__ import absolute_import + +# flake8: noqa + +# import apis into api package +from dynamic_servers.api.usage_api import UsageApi diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api/usage_api.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api/usage_api.py new file mode 100644 index 000000000000..0e74a6878b5a --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api/usage_api.py @@ -0,0 +1,536 @@ +# coding: utf-8 + +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import re # noqa: F401 +import sys # noqa: F401 + +# python 2 and python 3 compatibility library +import six + +from dynamic_servers.api_client import ApiClient +from dynamic_servers.exceptions import ( + ApiTypeError, + ApiValueError +) +from dynamic_servers.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + int, + none_type, + str, + validate_and_convert_types +) + + +class UsageApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def __custom_server( + self, + **kwargs + ): + """Use custom server # noqa: E501 + + Use custom server # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.custom_server(async_req=True) + >>> result = thread.get() + + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + {str: (bool, date, datetime, dict, float, int, list, str, none_type)} + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.custom_server = Endpoint( + settings={ + 'response_type': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), + 'auth': [], + 'endpoint_path': '/custom', + 'operation_id': 'custom_server', + 'http_method': 'GET', + 'servers': [ + { + 'url': "https://{server}.swagger.io:{port}/v2", + 'description': "No description provided", + 'variables': { + 'server': { + 'description': "No description provided", + 'default_value': "custom-petstore", + 'enum_values': [ + "custom-petstore", + "custom-qa-petstore", + "custom-dev-petstore" + ] + }, + 'port': { + 'description': "No description provided", + 'default_value': "8080", + 'enum_values': [ + "80", + "8080" + ] + } + } + }, + { + 'url': "https://localhost:8081/{version}", + 'description': "The local custom server", + 'variables': { + 'version': { + 'description': "No description provided", + 'default_value': "v2", + 'enum_values': [ + "v1", + "v2", + "v3" + ] + } + } + }, + { + 'url': "https://third.example.com/{prefix}", + 'description': "The local custom server", + 'variables': { + 'prefix': { + 'description': "No description provided", + 'default_value': "custom", + } + } + }, + ] + }, + params_map={ + 'all': [ + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + }, + 'attribute_map': { + }, + 'location_map': { + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__custom_server + ) + + def __default_server( + self, + **kwargs + ): + """Use default server # noqa: E501 + + Use default server # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.default_server(async_req=True) + >>> result = thread.get() + + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + {str: (bool, date, datetime, dict, float, int, list, str, none_type)} + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.default_server = Endpoint( + settings={ + 'response_type': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), + 'auth': [], + 'endpoint_path': '/default', + 'operation_id': 'default_server', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + }, + 'attribute_map': { + }, + 'location_map': { + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__default_server + ) + + +class Endpoint(object): + def __init__(self, settings=None, params_map=None, root_map=None, + headers_map=None, api_client=None, callable=None): + """Creates an endpoint + + Args: + settings (dict): see below key value pairs + 'response_type' (tuple/None): response type + 'auth' (list): a list of auth type keys + 'endpoint_path' (str): the endpoint path + 'operation_id' (str): endpoint string identifier + 'http_method' (str): POST/PUT/PATCH/GET etc + 'servers' (list): list of str servers that this endpoint is at + params_map (dict): see below key value pairs + 'all' (list): list of str endpoint parameter names + 'required' (list): list of required parameter names + 'nullable' (list): list of nullable parameter names + 'enum' (list): list of parameters with enum values + 'validation' (list): list of parameters with validations + root_map + 'validations' (dict): the dict mapping endpoint parameter tuple + paths to their validation dictionaries + 'allowed_values' (dict): the dict mapping endpoint parameter + tuple paths to their allowed_values (enum) dictionaries + 'openapi_types' (dict): param_name to openapi type + 'attribute_map' (dict): param_name to camelCase name + 'location_map' (dict): param_name to 'body', 'file', 'form', + 'header', 'path', 'query' + collection_format_map (dict): param_name to `csv` etc. + headers_map (dict): see below key value pairs + 'accept' (list): list of Accept header strings + 'content_type' (list): list of Content-Type header strings + api_client (ApiClient) api client instance + callable (function): the function which is invoked when the + Endpoint is called + """ + self.settings = settings + self.params_map = params_map + self.params_map['all'].extend([ + 'async_req', + '_host_index', + '_preload_content', + '_request_timeout', + '_return_http_data_only', + '_check_input_type', + '_check_return_type' + ]) + self.params_map['nullable'].extend(['_request_timeout']) + self.validations = root_map['validations'] + self.allowed_values = root_map['allowed_values'] + self.openapi_types = root_map['openapi_types'] + extra_types = { + 'async_req': (bool,), + '_host_index': (none_type, int), + '_preload_content': (bool,), + '_request_timeout': (none_type, int, (int,), [int]), + '_return_http_data_only': (bool,), + '_check_input_type': (bool,), + '_check_return_type': (bool,) + } + self.openapi_types.update(extra_types) + self.attribute_map = root_map['attribute_map'] + self.location_map = root_map['location_map'] + self.collection_format_map = root_map['collection_format_map'] + self.headers_map = headers_map + self.api_client = api_client + self.callable = callable + + def __validate_inputs(self, kwargs): + for param in self.params_map['enum']: + if param in kwargs: + check_allowed_values( + self.allowed_values, + (param,), + kwargs[param] + ) + + for param in self.params_map['validation']: + if param in kwargs: + check_validations( + self.validations, + (param,), + kwargs[param], + configuration=self.api_client.configuration + ) + + if kwargs['_check_input_type'] is False: + return + + for key, value in six.iteritems(kwargs): + fixed_val = validate_and_convert_types( + value, + self.openapi_types[key], + [key], + False, + kwargs['_check_input_type'], + configuration=self.api_client.configuration + ) + kwargs[key] = fixed_val + + def __gather_params(self, kwargs): + params = { + 'body': None, + 'collection_format': {}, + 'file': {}, + 'form': [], + 'header': {}, + 'path': {}, + 'query': [] + } + + for param_name, param_value in six.iteritems(kwargs): + param_location = self.location_map.get(param_name) + if param_location is None: + continue + if param_location: + if param_location == 'body': + params['body'] = param_value + continue + base_name = self.attribute_map[param_name] + if (param_location == 'form' and + self.openapi_types[param_name] == (file_type,)): + params['file'][param_name] = [param_value] + elif (param_location == 'form' and + self.openapi_types[param_name] == ([file_type],)): + # param_value is already a list + params['file'][param_name] = param_value + elif param_location in {'form', 'query'}: + param_value_full = (base_name, param_value) + params[param_location].append(param_value_full) + if param_location not in {'form', 'query'}: + params[param_location][base_name] = param_value + collection_format = self.collection_format_map.get(param_name) + if collection_format: + params['collection_format'][base_name] = collection_format + + return params + + def __call__(self, *args, **kwargs): + """ This method is invoked when endpoints are called + Example: + pet_api = PetApi() + pet_api.add_pet # this is an instance of the class Endpoint + pet_api.add_pet() # this invokes pet_api.add_pet.__call__() + which then invokes the callable functions stored in that endpoint at + pet_api.add_pet.callable or self.callable in this class + """ + return self.callable(self, *args, **kwargs) + + def call_with_http_info(self, **kwargs): + + try: + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'], self.api_client.configuration.server_variables + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) + except IndexError: + if self.settings['servers']: + raise ApiValueError( + "Invalid host index. Must be 0 <= index < %s" % + len(self.settings['servers']) + ) + _host = None + + for key, value in six.iteritems(kwargs): + if key not in self.params_map['all']: + raise ApiTypeError( + "Got an unexpected parameter '%s'" + " to method `%s`" % + (key, self.settings['operation_id']) + ) + # only throw this nullable ApiValueError if _check_input_type + # is False, if _check_input_type==True we catch this case + # in self.__validate_inputs + if (key not in self.params_map['nullable'] and value is None + and kwargs['_check_input_type'] is False): + raise ApiValueError( + "Value may not be None for non-nullable parameter `%s`" + " when calling `%s`" % + (key, self.settings['operation_id']) + ) + + for key in self.params_map['required']: + if key not in kwargs.keys(): + raise ApiValueError( + "Missing the required parameter `%s` when calling " + "`%s`" % (key, self.settings['operation_id']) + ) + + self.__validate_inputs(kwargs) + + params = self.__gather_params(kwargs) + + accept_headers_list = self.headers_map['accept'] + if accept_headers_list: + params['header']['Accept'] = self.api_client.select_header_accept( + accept_headers_list) + + content_type_headers_list = self.headers_map['content_type'] + if content_type_headers_list: + header_list = self.api_client.select_header_content_type( + content_type_headers_list) + params['header']['Content-Type'] = header_list + + return self.api_client.call_api( + self.settings['endpoint_path'], self.settings['http_method'], + params['path'], + params['query'], + params['header'], + body=params['body'], + post_params=params['form'], + files=params['file'], + response_type=self.settings['response_type'], + auth_settings=self.settings['auth'], + async_req=kwargs['async_req'], + _check_type=kwargs['_check_return_type'], + _return_http_data_only=kwargs['_return_http_data_only'], + _preload_content=kwargs['_preload_content'], + _request_timeout=kwargs['_request_timeout'], + _host=_host, + collection_formats=params['collection_format']) diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api_client.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api_client.py new file mode 100644 index 000000000000..fb8ce1e1f35a --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api_client.py @@ -0,0 +1,578 @@ +# coding: utf-8 +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from __future__ import absolute_import + +import json +import atexit +import mimetypes +from multiprocessing.pool import ThreadPool +import os +import re + +# python 2 and python 3 compatibility library +import six +from six.moves.urllib.parse import quote + +from dynamic_servers import rest +from dynamic_servers.configuration import Configuration +from dynamic_servers.exceptions import ApiValueError, ApiException +from dynamic_servers.model_utils import ( + ModelNormal, + ModelSimple, + ModelComposed, + date, + datetime, + deserialize_file, + file_type, + model_to_dict, + str, + validate_and_convert_types +) + + +class ApiClient(object): + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + :param pool_threads: The number of threads to use for async requests + to the API. More threads means more concurrent API requests. + """ + + # six.binary_type python2=str, python3=bytes + # six.text_type python2=unicode, python3=str + PRIMITIVE_TYPES = ( + (float, bool, six.binary_type, six.text_type) + six.integer_types + ) + _pool = None + + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None, pool_threads=1): + if configuration is None: + configuration = Configuration() + self.configuration = configuration + self.pool_threads = pool_threads + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + if self._pool: + self._pool.close() + self._pool.join() + self._pool = None + if hasattr(atexit, 'unregister'): + atexit.unregister(self.close) + + @property + def pool(self): + """Create thread pool on first request + avoids instantiating unused threadpool for blocking clients. + """ + if self._pool is None: + atexit.register(self.close) + self._pool = ThreadPool(self.pool_threads) + return self._pool + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + def __call_api( + self, resource_path, method, path_params=None, + query_params=None, header_params=None, body=None, post_params=None, + files=None, response_type=None, auth_settings=None, + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None, _host=None, + _check_type=None): + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples(path_params, + collection_formats) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + query_params = self.parameters_to_tuples(query_params, + collection_formats) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, + collection_formats) + post_params.extend(self.files_parameters(files)) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # auth setting + self.update_params_for_auth(header_params, query_params, + auth_settings, resource_path, method, body) + + # request url + if _host is None: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + try: + # perform request and return response + response_data = self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) + except ApiException as e: + e.body = e.body.decode('utf-8') if six.PY3 else e.body + raise e + + content_type = response_data.getheader('content-type') + + self.last_response = response_data + + return_data = response_data + + if not _preload_content: + return (return_data) + return return_data + + if six.PY3 and response_type not in ["file", "bytes"]: + match = None + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_data.data = response_data.data.decode(encoding) + + # deserialize response data + if response_type: + return_data = self.deserialize( + response_data, + response_type, + _check_type + ) + else: + return_data = None + + if _return_http_data_only: + return (return_data) + else: + return (return_data, response_data.status, + response_data.getheaders()) + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. + + If obj is None, return None. + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, list): + return [self.sanitize_for_serialization(sub_obj) + for sub_obj in obj] + elif isinstance(obj, tuple): + return tuple(self.sanitize_for_serialization(sub_obj) + for sub_obj in obj) + elif isinstance(obj, (datetime, date)): + return obj.isoformat() + + if isinstance(obj, dict): + obj_dict = obj + elif isinstance(obj, ModelNormal) or isinstance(obj, ModelComposed): + # Convert model obj to dict + # Convert attribute name to json key in + # model definition for request + obj_dict = model_to_dict(obj, serialize=True) + elif isinstance(obj, ModelSimple): + return self.sanitize_for_serialization(obj.value) + + return {key: self.sanitize_for_serialization(val) + for key, val in six.iteritems(obj_dict)} + + def deserialize(self, response, response_type, _check_type): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: For the response, a tuple containing: + valid classes + a list containing valid classes (for list schemas) + a dict containing a tuple of valid classes as the value + Example values: + (str,) + (Pet,) + (float, none_type) + ([int, none_type],) + ({str: (bool, str, int, float, date, datetime, str, none_type)},) + :param _check_type: boolean, whether to check the types of the data + received from the server + :type _check_type: bool + + :return: deserialized object. + """ + # handle file downloading + # save response body into a tmp file and return the instance + if response_type == (file_type,): + content_disposition = response.getheader("Content-Disposition") + return deserialize_file(response.data, self.configuration, + content_disposition=content_disposition) + + # fetch data from response object + try: + received_data = json.loads(response.data) + except ValueError: + received_data = response.data + + # store our data under the key of 'received_data' so users have some + # context if they are deserializing a string and the data type is wrong + deserialized_data = validate_and_convert_types( + received_data, + response_type, + ['received_data'], + True, + _check_type, + configuration=self.configuration + ) + return deserialized_data + + def call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_type=None, auth_settings=None, async_req=None, + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None, _host=None, + _check_type=None): + """Makes the HTTP request (synchronous) and returns deserialized data. + + To make an async_req request, set the async_req parameter. + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param response_type: For the response, a tuple containing: + valid classes + a list containing valid classes (for list schemas) + a dict containing a tuple of valid classes as the value + Example values: + (str,) + (Pet,) + (float, none_type) + ([int, none_type],) + ({str: (bool, str, int, float, date, datetime, str, none_type)},) + :param files: key -> field name, value -> a list of open file + objects for `multipart/form-data`. + :type files: dict + :param async_req bool: execute request asynchronously + :type async_req: bool, optional + :param _return_http_data_only: response data without head status code + and headers + :type _return_http_data_only: bool, optional + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :type collection_formats: dict, optional + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :type _preload_content: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _check_type: boolean describing if the data back from the server + should have its type checked. + :type _check_type: bool, optional + :return: + If async_req parameter is True, + the request will be called asynchronously. + The method will return the request thread. + If parameter async_req is False or missing, + then the method will return the response directly. + """ + if not async_req: + return self.__call_api(resource_path, method, + path_params, query_params, header_params, + body, post_params, files, + response_type, auth_settings, + _return_http_data_only, collection_formats, + _preload_content, _request_timeout, _host, + _check_type) + + return self.pool.apply_async(self.__call_api, (resource_path, + method, path_params, + query_params, + header_params, body, + post_params, files, + response_type, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + _host, _check_type)) + + def request(self, method, url, query_params=None, headers=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + """Makes the HTTP request using RESTClient.""" + if method == "GET": + return self.rest_client.GET(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "HEAD": + return self.rest_client.HEAD(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "OPTIONS": + return self.rest_client.OPTIONS(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "POST": + return self.rest_client.POST(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PUT": + return self.rest_client.PUT(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PATCH": + return self.rest_client.PATCH(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "DELETE": + return self.rest_client.DELETE(url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + else: + raise ApiValueError( + "http method must be `GET`, `HEAD`, `OPTIONS`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + def files_parameters(self, files=None): + """Builds form parameters. + + :param files: None or a dict with key=param_name and + value is a list of open file objects + :return: List of tuples of form parameters with file data + """ + if files is None: + return [] + + params = [] + for param_name, file_instances in six.iteritems(files): + if file_instances is None: + # if the file field is nullable, skip None values + continue + for file_instance in file_instances: + if file_instance is None: + # if the file field is nullable, skip None values + continue + if file_instance.closed is True: + raise ApiValueError( + "Cannot read a closed file. The passed in file_type " + "for %s must be open." % param_name + ) + filename = os.path.basename(file_instance.name) + filedata = file_instance.read() + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([param_name, tuple([filename, filedata, mimetype])])) + file_instance.close() + + return params + + def select_header_accept(self, accepts): + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return + + accepts = [x.lower() for x in accepts] + + if 'application/json' in accepts: + return 'application/json' + else: + return ', '.join(accepts) + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return 'application/json' + + content_types = [x.lower() for x in content_types] + + if 'application/json' in content_types or '*/*' in content_types: + return 'application/json' + else: + return content_types[0] + + def update_params_for_auth(self, headers, querys, auth_settings, + resource_path, method, body): + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param querys: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :param resource_path: A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method. + :param body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + """ + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + querys.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/apis/__init__.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/apis/__init__.py new file mode 100644 index 000000000000..74230e156deb --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/apis/__init__.py @@ -0,0 +1,18 @@ +# coding: utf-8 + +# flake8: noqa + +# Import all APIs into this package. +# If you have many APIs here with many many models used in each API this may +# raise a `RecursionError`. +# In order to avoid this, import only the API that you directly need like: +# +# from .api.pet_api import PetApi +# +# or import this package, but before doing it, use: +# +# import sys +# sys.setrecursionlimit(n) + +# Import APIs into API package: +from dynamic_servers.api.usage_api import UsageApi diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py new file mode 100644 index 000000000000..38a3be5c1f4a --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py @@ -0,0 +1,464 @@ +# coding: utf-8 + +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import copy +import logging +import multiprocessing +import sys +import urllib3 + +import six +from six.moves import http_client as httplib +from dynamic_servers.exceptions import ApiValueError + + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +class Configuration(object): + """NOTE: This class is auto generated by OpenAPI Generator + + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param host: Base url + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer) + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication + :param password: Password for HTTP basic authentication + :param discard_unknown_keys: Boolean value indicating whether to discard + unknown properties. A server may send a response that includes additional + properties that are not known by the client in the following scenarios: + 1. The OpenAPI document is incomplete, i.e. it does not match the server + implementation. + 2. The client was generated using an older version of the OpenAPI document + and the server has been upgraded since then. + If a schema in the OpenAPI document defines the additionalProperties attribute, + then all undeclared properties received by the server are injected into the + additional properties map. In that case, there are undeclared properties, and + nothing to discard. + :param disabled_client_side_validations (string): Comma-separated list of + JSON schema validation keywords to disable JSON schema structural validation + rules. The following keywords may be specified: multipleOf, maximum, + exclusiveMaximum, minimum, exclusiveMinimum, maxLength, minLength, pattern, + maxItems, minItems. + By default, the validation is performed for data generated locally by the client + and data received from the server, independent of any validation performed by + the server side. If the input data does not satisfy the JSON schema validation + rules specified in the OpenAPI document, an exception is raised. + If disabled_client_side_validations is set, structural validation is + disabled. This can be useful to troubleshoot data validation problem, such as + when the OpenAPI document validation rules do not match the actual API data + received by the server. + + """ + + _default = None + + def __init__(self, host=None, + api_key=None, api_key_prefix=None, + username=None, password=None, + discard_unknown_keys=False, + disabled_client_side_validations="", + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ): + """Constructor + """ + self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.discard_unknown_keys = discard_unknown_keys + self.disabled_client_side_validations = disabled_client_side_validations + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("dynamic_servers") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + self.debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = None + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + + self.proxy = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = None + """Adding retries to override urllib3 default value 3 + """ + # Disable client side validation + self.client_side_validation = True + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name, value): + object.__setattr__(self, name, value) + if name == 'disabled_client_side_validations': + s = set(filter(None, value.split(','))) + for v in s: + if v not in JSON_SCHEMA_VALIDATION_KEYWORDS: + raise ApiValueError( + "Invalid keyword: '{0}''".format(v)) + self._disabled_client_side_validations = s + + @classmethod + def set_default(cls, default): + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = copy.deepcopy(default) + + @classmethod + def get_default_copy(cls): + """Return new instance of configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration passed by the set_default method. + + :return: The configuration object. + """ + if cls._default is not None: + return copy.deepcopy(cls._default) + return Configuration() + + @property + def logger_file(self): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in six.iteritems(self.logger): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in six.iteritems(self.logger): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in six.iteritems(self.logger): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier): + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + def get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self): + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth = {} + return auth + + def to_debug_report(self): + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 1.0.0\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self): + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "http://{server}.swagger.io:{port}/v2", + 'description': "petstore server", + 'variables': { + 'server': { + 'description': "No description provided", + 'default_value': "petstore", + 'enum_values': [ + "petstore", + "qa-petstore", + "dev-petstore" + ] + }, + 'port': { + 'description': "No description provided", + 'default_value': "80", + 'enum_values': [ + "80", + "8080" + ] + } + } + }, + { + 'url': "https://localhost:8080/{version}", + 'description': "The local server", + 'variables': { + 'version': { + 'description': "No description provided", + 'default_value': "v1", + 'enum_values': [ + "v1", + "v2", + "v3" + ] + } + } + } + ] + + def get_host_from_settings(self, index, variables=None, servers=None): + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self): + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/exceptions.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/exceptions.py new file mode 100644 index 000000000000..8cafe7240c1d --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/exceptions.py @@ -0,0 +1,139 @@ +# coding: utf-8 + +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import six + + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None): + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None): + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + if http_resp: + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data + self.headers = http_resp.getheaders() + else: + self.status = status + self.reason = reason + self.body = None + self.headers = None + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.body: + error_message += "HTTP response body: {0}\n".format(self.body) + + return error_message + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, six.integer_types): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/model/__init__.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/model/__init__.py new file mode 100644 index 000000000000..cfe32b784926 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/model/__init__.py @@ -0,0 +1,5 @@ +# we can not import model classes here because that would create a circular +# reference which would not work in python2 +# do not import all models into this module because that uses a lot of memory and stack frames +# if you need the ability to import all models from one package, import them with +# from {{packageName}.models import ModelA, ModelB diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/model_utils.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/model_utils.py new file mode 100644 index 000000000000..adaff897b525 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/model_utils.py @@ -0,0 +1,1770 @@ +# coding: utf-8 + +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from datetime import date, datetime # noqa: F401 +import inspect +import os +import pprint +import re +import tempfile + +from dateutil.parser import parse +import six + +from dynamic_servers.exceptions import ( + ApiKeyError, + ApiAttributeError, + ApiTypeError, + ApiValueError, +) + +none_type = type(None) +if six.PY3: + import io + file_type = io.IOBase + # these are needed for when other modules import str and int from here + str = str + int = int +else: + file_type = file # noqa: F821 + str_py2 = str + unicode_py2 = unicode # noqa: F821 + long_py2 = long # noqa: F821 + int_py2 = int + # this requires that the future library is installed + from builtins import int, str + + +class cached_property(object): + # this caches the result of the function call for fn with no inputs + # use this as a decorator on fuction methods that you want converted + # into cached properties + result_key = '_results' + + def __init__(self, fn): + self._fn = fn + + def __get__(self, instance, cls=None): + try: + return vars(self)[self.result_key] + except KeyError: + result = self._fn() + setattr(self, self.result_key, result) + return result + + +class OpenApiModel(object): + """The base class for all OpenAPIModels""" + + def set_attribute(self, name, value): + # this is only used to set properties on self + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + + if name in self.openapi_types: + required_types_mixed = self.openapi_types[name] + elif self.additional_properties_type is None: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + path_to_item + ) + elif self.additional_properties_type is not None: + required_types_mixed = self.additional_properties_type + + if get_simple_class(name) != str: + error_msg = type_error_message( + var_name=name, + var_value=name, + valid_classes=(str,), + key_type=True + ) + raise ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=(str,), + key_type=True + ) + + if self._check_type: + value = validate_and_convert_types( + value, required_types_mixed, path_to_item, self._spec_property_naming, + self._check_type, configuration=self._configuration) + if (name,) in self.allowed_values: + check_allowed_values( + self.allowed_values, + (name,), + value + ) + if (name,) in self.validations: + check_validations( + self.validations, + (name,), + value, + self._configuration + ) + self.__dict__['_data_store'][name] = value + + def __setitem__(self, name, value): + """this allows us to set values with instance[field_name] = val""" + self.__setattr__(name, value) + + def __getitem__(self, name): + """this allows us to get a value with val = instance[field_name]""" + return self.__getattr__(name) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other + + def __new__(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1 and args[0] is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return super(OpenApiModel, cls).__new__(cls) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return super(OpenApiModel, cls).__new__(cls) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = super(OpenApiModel, cls).__new__(cls) + self_inst.__init__(*args, **kwargs) + + new_inst = new_cls.__new__(new_cls, *args, **kwargs) + new_inst.__init__(*args, **kwargs) + return new_inst + + +class ModelSimple(OpenApiModel): + """the parent class of models whose type != object in their + swagger/openapi""" + + def __setattr__(self, name, value): + """this allows us to set a value with instance.field_name = val""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def __getattr__(self, name): + """this allows us to get a value with val = instance.field_name""" + if name in self.required_properties: + return self.__dict__[name] + + if name in self.__dict__['_data_store']: + return self.__dict__['_data_store'][name] + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [name] + ) + + def to_str(self): + """Returns the string representation of the model""" + return str(self.value) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + this_val = self._data_store['value'] + that_val = other._data_store['value'] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not six.PY3 and len(types) == 2 and unicode in types: # noqa: F821 + vals_equal = ( + this_val.encode('utf-8') == that_val.encode('utf-8') + ) + if not vals_equal: + return False + return True + + +class ModelNormal(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi""" + + def __setattr__(self, name, value): + """this allows us to set a value with instance.field_name = val""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def __getattr__(self, name): + """this allows us to get a value with val = instance.field_name""" + if name in self.required_properties: + return self.__dict__[name] + + if name in self.__dict__['_data_store']: + return self.__dict__['_data_store'][name] + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [name] + ) + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in six.iteritems(self._data_store): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if (not six.PY3 and + len(types) == 2 and unicode in types): # noqa: F821 + vals_equal = ( + this_val.encode('utf-8') == that_val.encode('utf-8') + ) + if not vals_equal: + return False + return True + + +class ModelComposed(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi and have oneOf/allOf/anyOf + + When one sets a property we use var_name_to_model_instances to store the value in + the correct class instances + run any type checking + validation code. + When one gets a property we use var_name_to_model_instances to get the value + from the correct class instances. + This allows multiple composed schemas to contain the same property with additive + constraints on the value. + + _composed_schemas (dict) stores the anyOf/allOf/oneOf classes + key (str): allOf/oneOf/anyOf + value (list): the classes in the XOf definition. + Note: none_type can be included when the openapi document version >= 3.1.0 + _composed_instances (list): stores a list of instances of the composed schemas + defined in _composed_schemas. When properties are accessed in the self instance, + they are returned from the self._data_store or the data stores in the instances + in self._composed_schemas + _var_name_to_model_instances (dict): maps between a variable name on self and + the composed instances (self included) which contain that data + key (str): property name + value (list): list of class instances, self or instances in _composed_instances + which contain the value that the key is referring to. + """ + + def __setattr__(self, name, value): + """this allows us to set a value with instance.field_name = val""" + if name in self.required_properties: + self.__dict__[name] = value + return + + # set the attribute on the correct instance + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + if model_instances: + for model_instance in model_instances: + if model_instance == self: + self.set_attribute(name, value) + else: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = ( + model_instance + ) + return None + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + path_to_item + ) + + def __getattr__(self, name): + """this allows us to get a value with val = instance.field_name""" + if name in self.required_properties: + return self.__dict__[name] + + # get the attribute from the correct instance + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + values = [] + # A composed model stores child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. A named property can exist in + # multiple child models. If the property is present in more than one + # child model, the value must be the same across all the child models. + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + v = model_instance._data_store[name] + if v not in values: + values.append(v) + len_values = len(values) + if len_values == 0: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + path_to_item + ) + elif len_values == 1: + return values[0] + elif len_values > 1: + raise ApiValueError( + "Values stored for property {0} in {1} differ when looking " + "at self and self's composed instances. All values must be " + "the same".format(name, type(self).__name__), + path_to_item + ) + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in six.iteritems(self._data_store): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if (not six.PY3 and + len(types) == 2 and unicode in types): # noqa: F821 + vals_equal = ( + this_val.encode('utf-8') == that_val.encode('utf-8') + ) + if not vals_equal: + return False + return True + + +COERCION_INDEX_BY_TYPE = { + ModelComposed: 0, + ModelNormal: 1, + ModelSimple: 2, + none_type: 3, # The type of 'None'. + list: 4, + dict: 5, + float: 6, + int: 7, + bool: 8, + datetime: 9, + date: 10, + str: 11, + file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. +} + +# these are used to limit what type conversions we try to do +# when we have a valid type already and we want to try converting +# to another type +UPCONVERSION_TYPE_PAIRS = ( + (str, datetime), + (str, date), + (int, float), # A float may be serialized as an integer, e.g. '3' is a valid serialized float. + (list, ModelComposed), + (dict, ModelComposed), + (list, ModelNormal), + (dict, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), +) + +COERCIBLE_TYPE_PAIRS = { + False: ( # client instantiation of a model with client data + # (dict, ModelComposed), + # (list, ModelComposed), + # (dict, ModelNormal), + # (list, ModelNormal), + # (str, ModelSimple), + # (int, ModelSimple), + # (float, ModelSimple), + # (list, ModelSimple), + # (str, int), + # (str, float), + # (str, datetime), + # (str, date), + # (int, str), + # (float, str), + ), + True: ( # server -> client data + (dict, ModelComposed), + (list, ModelComposed), + (dict, ModelNormal), + (list, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), + # (str, int), + # (str, float), + (str, datetime), + (str, date), + # (int, str), + # (float, str), + (str, file_type) + ), +} + + +def get_simple_class(input_value): + """Returns an input_value's simple class that we will use for type checking + Python2: + float and int will return int, where int is the python3 int backport + str and unicode will return str, where str is the python3 str backport + Note: float and int ARE both instances of int backport + Note: str_py2 and unicode_py2 are NOT both instances of str backport + + Args: + input_value (class/class_instance): the item for which we will return + the simple class + """ + if isinstance(input_value, type): + # input_value is a class + return input_value + elif isinstance(input_value, tuple): + return tuple + elif isinstance(input_value, list): + return list + elif isinstance(input_value, dict): + return dict + elif isinstance(input_value, none_type): + return none_type + elif isinstance(input_value, file_type): + return file_type + elif isinstance(input_value, bool): + # this must be higher than the int check because + # isinstance(True, int) == True + return bool + elif isinstance(input_value, int): + # for python2 input_value==long_instance -> return int + # where int is the python3 int backport + return int + elif isinstance(input_value, datetime): + # this must be higher than the date check because + # isinstance(datetime_instance, date) == True + return datetime + elif isinstance(input_value, date): + return date + elif (six.PY2 and isinstance(input_value, (str_py2, unicode_py2, str)) or + isinstance(input_value, str)): + return str + return type(input_value) + + +def check_allowed_values(allowed_values, input_variable_path, input_values): + """Raises an exception if the input_values are not allowed + + Args: + allowed_values (dict): the allowed_values dict + input_variable_path (tuple): the path to the input variable + input_values (list/str/int/float/date/datetime): the values that we + are checking to see if they are in allowed_values + """ + these_allowed_values = list(allowed_values[input_variable_path].values()) + if (isinstance(input_values, list) + and not set(input_values).issubset( + set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values) - set(these_allowed_values))), + raise ApiValueError( + "Invalid values for `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (isinstance(input_values, dict) + and not set( + input_values.keys()).issubset(set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values.keys()) - set(these_allowed_values))) + raise ApiValueError( + "Invalid keys in `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (not isinstance(input_values, (list, dict)) + and input_values not in these_allowed_values): + raise ApiValueError( + "Invalid value for `%s` (%s), must be one of %s" % + ( + input_variable_path[0], + input_values, + these_allowed_values + ) + ) + + +def is_json_validation_enabled(schema_keyword, configuration=None): + """Returns true if JSON schema validation is enabled for the specified + validation keyword. This can be used to skip JSON schema structural validation + as requested in the configuration. + + Args: + schema_keyword (string): the name of a JSON schema validation keyword. + configuration (Configuration): the configuration class. + """ + + return (configuration is None or + not hasattr(configuration, '_disabled_client_side_validations') or + schema_keyword not in configuration._disabled_client_side_validations) + + +def check_validations( + validations, input_variable_path, input_values, + configuration=None): + """Raises an exception if the input_values are invalid + + Args: + validations (dict): the validation dictionary. + input_variable_path (tuple): the path to the input variable. + input_values (list/str/int/float/date/datetime): the values that we + are checking. + configuration (Configuration): the configuration class. + """ + + current_validations = validations[input_variable_path] + if (is_json_validation_enabled('multipleOf', configuration) and + 'multiple_of' in current_validations and + isinstance(input_values, (int, float)) and + not (float(input_values) / current_validations['multiple_of']).is_integer()): + # Note 'multipleOf' will be as good as the floating point arithmetic. + raise ApiValueError( + "Invalid value for `%s`, value must be a multiple of " + "`%s`" % ( + input_variable_path[0], + current_validations['multiple_of'] + ) + ) + + if (is_json_validation_enabled('maxLength', configuration) and + 'max_length' in current_validations and + len(input_values) > current_validations['max_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['max_length'] + ) + ) + + if (is_json_validation_enabled('minLength', configuration) and + 'min_length' in current_validations and + len(input_values) < current_validations['min_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be greater than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['min_length'] + ) + ) + + if (is_json_validation_enabled('maxItems', configuration) and + 'max_items' in current_validations and + len(input_values) > current_validations['max_items']): + raise ApiValueError( + "Invalid value for `%s`, number of items must be less than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['max_items'] + ) + ) + + if (is_json_validation_enabled('minItems', configuration) and + 'min_items' in current_validations and + len(input_values) < current_validations['min_items']): + raise ValueError( + "Invalid value for `%s`, number of items must be greater than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['min_items'] + ) + ) + + items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', + 'inclusive_minimum') + if (any(item in current_validations for item in items)): + if isinstance(input_values, list): + max_val = max(input_values) + min_val = min(input_values) + elif isinstance(input_values, dict): + max_val = max(input_values.values()) + min_val = min(input_values.values()) + else: + max_val = input_values + min_val = input_values + + if (is_json_validation_enabled('exclusiveMaximum', configuration) and + 'exclusive_maximum' in current_validations and + max_val >= current_validations['exclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than `%s`" % ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('maximum', configuration) and + 'inclusive_maximum' in current_validations and + max_val > current_validations['inclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['inclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('exclusiveMinimum', configuration) and + 'exclusive_minimum' in current_validations and + min_val <= current_validations['exclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than `%s`" % + ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('minimum', configuration) and + 'inclusive_minimum' in current_validations and + min_val < current_validations['inclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than or equal " + "to `%s`" % ( + input_variable_path[0], + current_validations['inclusive_minimum'] + ) + ) + flags = current_validations.get('regex', {}).get('flags', 0) + if (is_json_validation_enabled('pattern', configuration) and + 'regex' in current_validations and + not re.search(current_validations['regex']['pattern'], + input_values, flags=flags)): + err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( + input_variable_path[0], + current_validations['regex']['pattern'] + ) + if flags != 0: + # Don't print the regex flags if the flags are not + # specified in the OAS document. + err_msg = r"%s with flags=`%s`" % (err_msg, flags) + raise ApiValueError(err_msg) + + +def order_response_types(required_types): + """Returns the required types sorted in coercion order + + Args: + required_types (list/tuple): collection of classes or instance of + list or dict with class information inside it. + + Returns: + (list): coercion order sorted collection of classes or instance + of list or dict with class information inside it. + """ + + def index_getter(class_or_instance): + if isinstance(class_or_instance, list): + return COERCION_INDEX_BY_TYPE[list] + elif isinstance(class_or_instance, dict): + return COERCION_INDEX_BY_TYPE[dict] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelComposed)): + return COERCION_INDEX_BY_TYPE[ModelComposed] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelNormal)): + return COERCION_INDEX_BY_TYPE[ModelNormal] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelSimple)): + return COERCION_INDEX_BY_TYPE[ModelSimple] + elif class_or_instance in COERCION_INDEX_BY_TYPE: + return COERCION_INDEX_BY_TYPE[class_or_instance] + raise ApiValueError("Unsupported type: %s" % class_or_instance) + + sorted_types = sorted( + required_types, + key=lambda class_or_instance: index_getter(class_or_instance) + ) + return sorted_types + + +def remove_uncoercible(required_types_classes, current_item, spec_property_naming, + must_convert=True): + """Only keeps the type conversions that are possible + + Args: + required_types_classes (tuple): tuple of classes that are required + these should be ordered by COERCION_INDEX_BY_TYPE + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + current_item (any): the current item (input data) to be converted + + Keyword Args: + must_convert (bool): if True the item to convert is of the wrong + type and we want a big list of coercibles + if False, we want a limited list of coercibles + + Returns: + (list): the remaining coercible required types, classes only + """ + current_type_simple = get_simple_class(current_item) + + results_classes = [] + for required_type_class in required_types_classes: + # convert our models to OpenApiModel + required_type_class_simplified = required_type_class + if isinstance(required_type_class_simplified, type): + if issubclass(required_type_class_simplified, ModelComposed): + required_type_class_simplified = ModelComposed + elif issubclass(required_type_class_simplified, ModelNormal): + required_type_class_simplified = ModelNormal + elif issubclass(required_type_class_simplified, ModelSimple): + required_type_class_simplified = ModelSimple + + if required_type_class_simplified == current_type_simple: + # don't consider converting to one's own class + continue + + class_pair = (current_type_simple, required_type_class_simplified) + if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: + results_classes.append(required_type_class) + elif class_pair in UPCONVERSION_TYPE_PAIRS: + results_classes.append(required_type_class) + return results_classes + + +def get_required_type_classes(required_types_mixed): + """Converts the tuple required_types into a tuple and a dict described + below + + Args: + required_types_mixed (tuple/list): will contain either classes or + instance of list or dict + + Returns: + (valid_classes, dict_valid_class_to_child_types_mixed): + valid_classes (tuple): the valid classes that the current item + should be + dict_valid_class_to_child_types_mixed (doct): + valid_class (class): this is the key + child_types_mixed (list/dict/tuple): describes the valid child + types + """ + valid_classes = [] + child_req_types_by_current_type = {} + for required_type in required_types_mixed: + if isinstance(required_type, list): + valid_classes.append(list) + child_req_types_by_current_type[list] = required_type + elif isinstance(required_type, tuple): + valid_classes.append(tuple) + child_req_types_by_current_type[tuple] = required_type + elif isinstance(required_type, dict): + valid_classes.append(dict) + child_req_types_by_current_type[dict] = required_type[str] + else: + valid_classes.append(required_type) + return tuple(valid_classes), child_req_types_by_current_type + + +def change_keys_js_to_python(input_dict, model_class): + """ + Converts from javascript_key keys in the input_dict to python_keys in + the output dict using the mapping in model_class. + If the input_dict contains a key which does not declared in the model_class, + the key is added to the output dict as is. The assumption is the model_class + may have undeclared properties (additionalProperties attribute in the OAS + document). + """ + + if getattr(model_class, 'attribute_map', None) is None: + return input_dict + output_dict = {} + reversed_attr_map = {value: key for key, value in + model_class.attribute_map.items()} + for javascript_key, value in input_dict.items(): + python_key = reversed_attr_map.get(javascript_key) + if python_key is None: + # if the key is unknown, it is in error or it is an + # additionalProperties variable + python_key = javascript_key + output_dict[python_key] = value + return output_dict + + +def get_type_error(var_value, path_to_item, valid_classes, key_type=False): + error_msg = type_error_message( + var_name=path_to_item[-1], + var_value=var_value, + valid_classes=valid_classes, + key_type=key_type + ) + return ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=valid_classes, + key_type=key_type + ) + + +def deserialize_primitive(data, klass, path_to_item): + """Deserializes string to primitive type. + + :param data: str/int/float + :param klass: str/class the class to convert to + + :return: int, float, str, bool, date, datetime + """ + additional_message = "" + try: + if klass in {datetime, date}: + additional_message = ( + "If you need your parameter to have a fallback " + "string value, please set its type as `type: {}` in your " + "spec. That allows the value to be any type. " + ) + if klass == datetime: + if len(data) < 8: + raise ValueError("This is not a datetime") + # The string should be in iso8601 datetime format. + parsed_datetime = parse(data) + date_only = ( + parsed_datetime.hour == 0 and + parsed_datetime.minute == 0 and + parsed_datetime.second == 0 and + parsed_datetime.tzinfo is None and + 8 <= len(data) <= 10 + ) + if date_only: + raise ValueError("This is a date, not a datetime") + return parsed_datetime + elif klass == date: + if len(data) < 8: + raise ValueError("This is not a date") + return parse(data).date() + else: + converted_value = klass(data) + if isinstance(data, str) and klass == float: + if str(converted_value) != data: + # '7' -> 7.0 -> '7.0' != '7' + raise ValueError('This is not a float') + return converted_value + except (OverflowError, ValueError) as ex: + # parse can raise OverflowError + six.raise_from(ApiValueError( + "{0}Failed to parse {1} as {2}".format( + additional_message, repr(data), get_py3_class_name(klass) + ), + path_to_item=path_to_item + ), ex) + + +def get_discriminator_class(model_class, + discr_name, + discr_value, cls_visited): + """Returns the child class specified by the discriminator. + + Args: + model_class (OpenApiModel): the model class. + discr_name (string): the name of the discriminator property. + discr_value (any): the discriminator value. + cls_visited (list): list of model classes that have been visited. + Used to determine the discriminator class without + visiting circular references indefinitely. + + Returns: + used_model_class (class/None): the chosen child class that will be used + to deserialize the data, for example dog.Dog. + If a class is not found, None is returned. + """ + + if model_class in cls_visited: + # The class has already been visited and no suitable class was found. + return None + cls_visited.append(model_class) + used_model_class = None + if discr_name in model_class.discriminator: + class_name_to_discr_class = model_class.discriminator[discr_name] + used_model_class = class_name_to_discr_class.get(discr_value) + if used_model_class is None: + # We didn't find a discriminated class in class_name_to_discr_class. + # So look in the ancestor or descendant discriminators + # The discriminator mapping may exist in a descendant (anyOf, oneOf) + # or ancestor (allOf). + # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat + # hierarchy, the discriminator mappings may be defined at any level + # in the hierarchy. + # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig + # if we try to make BasquePig from mammal, we need to travel through + # the oneOf descendant discriminators to find BasquePig + descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \ + model_class._composed_schemas.get('anyOf', ()) + ancestor_classes = model_class._composed_schemas.get('allOf', ()) + possible_classes = descendant_classes + ancestor_classes + for cls in possible_classes: + # Check if the schema has inherited discriminators. + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + used_model_class = get_discriminator_class( + cls, discr_name, discr_value, cls_visited) + if used_model_class is not None: + return used_model_class + return used_model_class + + +def deserialize_model(model_data, model_class, path_to_item, check_type, + configuration, spec_property_naming): + """Deserializes model_data to model instance. + + Args: + model_data (list/dict): data to instantiate the model + model_class (OpenApiModel): the model class + path_to_item (list): path to the model in the received data + check_type (bool): whether to check the data tupe for the values in + the model + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + + Returns: + model instance + + Raise: + ApiTypeError + ApiValueError + ApiKeyError + """ + + kw_args = dict(_check_type=check_type, + _path_to_item=path_to_item, + _configuration=configuration, + _spec_property_naming=spec_property_naming) + + if issubclass(model_class, ModelSimple): + instance = model_class(value=model_data, **kw_args) + return instance + if isinstance(model_data, list): + instance = model_class(*model_data, **kw_args) + if isinstance(model_data, dict): + kw_args.update(model_data) + instance = model_class(**kw_args) + return instance + + +def deserialize_file(response_data, configuration, content_disposition=None): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + Args: + param response_data (str): the file data to write + configuration (Configuration): the instance to use to convert files + + Keyword Args: + content_disposition (str): the value of the Content-Disposition + header + + Returns: + (file_type): the deserialized file which is open + The user is responsible for closing and reading the file + """ + fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + if content_disposition: + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition).group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + if six.PY3 and isinstance(response_data, str): + # in python3 change str to bytes so we can write it + response_data = response_data.encode('utf-8') + f.write(response_data) + + f = open(path, "rb") + return f + + +def attempt_convert_item(input_value, valid_classes, path_to_item, + configuration, spec_property_naming, key_type=False, + must_convert=False, check_type=True): + """ + Args: + input_value (any): the data to convert + valid_classes (any): the classes that are valid + path_to_item (list): the path to the item to convert + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + key_type (bool): if True we need to convert a key type (not supported) + must_convert (bool): if True we must convert + check_type (bool): if True we check the type or the returned data in + ModelComposed/ModelNormal/ModelSimple instances + + Returns: + instance (any) the fixed item + + Raises: + ApiTypeError + ApiValueError + ApiKeyError + """ + valid_classes_ordered = order_response_types(valid_classes) + valid_classes_coercible = remove_uncoercible( + valid_classes_ordered, input_value, spec_property_naming) + if not valid_classes_coercible or key_type: + # we do not handle keytype errors, json will take care + # of this for us + if configuration is None or not configuration.discard_unknown_keys: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=key_type) + for valid_class in valid_classes_coercible: + try: + if issubclass(valid_class, OpenApiModel): + return deserialize_model(input_value, valid_class, + path_to_item, check_type, + configuration, spec_property_naming) + elif valid_class == file_type: + return deserialize_file(input_value, configuration) + return deserialize_primitive(input_value, valid_class, + path_to_item) + except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: + if must_convert: + raise conversion_exc + # if we have conversion errors when must_convert == False + # we ignore the exception and move on to the next class + continue + # we were unable to convert, must_convert == False + return input_value + + +def is_type_nullable(input_type): + """ + Returns true if None is an allowed value for the specified input_type. + + A type is nullable if at least one of the following conditions is true: + 1. The OAS 'nullable' attribute has been specified, + 1. The type is the 'null' type, + 1. The type is a anyOf/oneOf composed schema, and a child schema is + the 'null' type. + Args: + input_type (type): the class of the input_value that we are + checking + Returns: + bool + """ + if input_type is none_type: + return True + if issubclass(input_type, OpenApiModel) and input_type._nullable: + return True + if issubclass(input_type, ModelComposed): + # If oneOf/anyOf, check if the 'null' type is one of the allowed types. + for t in input_type._composed_schemas.get('oneOf', ()): + if is_type_nullable(t): return True + for t in input_type._composed_schemas.get('anyOf', ()): + if is_type_nullable(t): return True + return False + + +def is_valid_type(input_class_simple, valid_classes): + """ + Args: + input_class_simple (class): the class of the input_value that we are + checking + valid_classes (tuple): the valid classes that the current item + should be + Returns: + bool + """ + valid_type = input_class_simple in valid_classes + if not valid_type and ( + issubclass(input_class_simple, OpenApiModel) or + input_class_simple is none_type): + for valid_class in valid_classes: + if input_class_simple is none_type and is_type_nullable(valid_class): + # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. + return True + if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): + continue + discr_propertyname_py = list(valid_class.discriminator.keys())[0] + discriminator_classes = ( + valid_class.discriminator[discr_propertyname_py].values() + ) + valid_type = is_valid_type(input_class_simple, discriminator_classes) + if valid_type: + return True + return valid_type + + +def validate_and_convert_types(input_value, required_types_mixed, path_to_item, + spec_property_naming, _check_type, configuration=None): + """Raises a TypeError is there is a problem, otherwise returns value + + Args: + input_value (any): the data to validate/convert + required_types_mixed (list/dict/tuple): A list of + valid classes, or a list tuples of valid classes, or a dict where + the value is a tuple of value classes + path_to_item: (list) the path to the data being validated + this stores a list of keys or indices to get to the data being + validated + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + _check_type: (boolean) if true, type will be checked and conversion + will be attempted. + configuration: (Configuration): the configuration class to use + when converting file_type items. + If passed, conversion will be attempted when possible + If not passed, no conversions will be attempted and + exceptions will be raised + + Returns: + the correctly typed value + + Raises: + ApiTypeError + """ + results = get_required_type_classes(required_types_mixed) + valid_classes, child_req_types_by_current_type = results + + input_class_simple = get_simple_class(input_value) + valid_type = is_valid_type(input_class_simple, valid_classes) + if not valid_type: + if configuration: + # if input_value is not valid_type try to convert it + converted_instance = attempt_convert_item( + input_value, + valid_classes, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=True + ) + return converted_instance + else: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=False) + + # input_value's type is in valid_classes + if len(valid_classes) > 1 and configuration: + # there are valid classes which are not the current class + valid_classes_coercible = remove_uncoercible( + valid_classes, input_value, spec_property_naming, must_convert=False) + if valid_classes_coercible: + converted_instance = attempt_convert_item( + input_value, + valid_classes_coercible, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=False + ) + return converted_instance + + if child_req_types_by_current_type == {}: + # all types are of the required types and there are no more inner + # variables left to look at + return input_value + inner_required_types = child_req_types_by_current_type.get( + type(input_value) + ) + if inner_required_types is None: + # for this type, there are not more inner variables left to look at + return input_value + if isinstance(input_value, list): + if input_value == []: + # allow an empty list + return input_value + for index, inner_value in enumerate(input_value): + inner_path = list(path_to_item) + inner_path.append(index) + input_value[index] = validate_and_convert_types( + inner_value, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + elif isinstance(input_value, dict): + if input_value == {}: + # allow an empty dict + return input_value + for inner_key, inner_val in six.iteritems(input_value): + inner_path = list(path_to_item) + inner_path.append(inner_key) + if get_simple_class(inner_key) != str: + raise get_type_error(inner_key, inner_path, valid_classes, + key_type=True) + input_value[inner_key] = validate_and_convert_types( + inner_val, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + return input_value + + +def model_to_dict(model_instance, serialize=True): + """Returns the model properties as a dict + + Args: + model_instance (one of your model instances): the model instance that + will be converted to a dict. + + Keyword Args: + serialize (bool): if True, the keys in the dict will be values from + attribute_map + """ + result = {} + + model_instances = [model_instance] + if model_instance._composed_schemas: + model_instances.extend(model_instance._composed_instances) + for model_instance in model_instances: + for attr, value in six.iteritems(model_instance._data_store): + if serialize: + # we use get here because additional property key names do not + # exist in attribute_map + attr = model_instance.attribute_map.get(attr, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: model_to_dict(x, serialize=serialize) + if hasattr(x, '_data_store') else x, value + )) + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], + model_to_dict(item[1], serialize=serialize)) + if hasattr(item[1], '_data_store') else item, + value.items() + )) + elif hasattr(value, '_data_store'): + result[attr] = model_to_dict(value, serialize=serialize) + else: + result[attr] = value + + return result + + +def type_error_message(var_value=None, var_name=None, valid_classes=None, + key_type=None): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + """ + key_or_value = 'value' + if key_type: + key_or_value = 'key' + valid_classes_phrase = get_valid_classes_phrase(valid_classes) + msg = ( + "Invalid type for variable '{0}'. Required {1} type {2} and " + "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + ) + return msg + + +def get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed + Note: Adds the extra valid classes in python2 + """ + all_classes = list(input_classes) + if six.PY2 and str in input_classes: + all_classes.extend([str_py2, unicode_py2]) + if six.PY2 and int in input_classes: + all_classes.extend([int_py2, long_py2]) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return 'is {0}'.format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + +def get_py3_class_name(input_class): + if six.PY2: + if input_class == str: + return 'str' + elif input_class == int: + return 'int' + return input_class.__name__ + + +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(self, *args, **kwargs): + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, self.__class__) + return fn(self, *args, **kwargs) + return wrapped_init + + +def get_allof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): var_name to var_value + used to make instances + + Returns + composed_instances (list) + """ + composed_instances = [] + for allof_class in self._composed_schemas['allOf']: + + # no need to handle changing js keys to python because + # for composed schemas, allof parameters are included in the + # composed schema and were changed to python keys in __new__ + # extract a dict of only required keys from fixed_model_args + kwargs = {} + var_names = set(allof_class.openapi_types.keys()) + for var_name in var_names: + if var_name in model_args: + kwargs[var_name] = model_args[var_name] + + # and use it to make the instance + kwargs.update(constant_args) + try: + allof_instance = allof_class(**kwargs) + composed_instances.append(allof_instance) + except Exception as ex: + six.raise_from(ApiValueError( + "Invalid inputs given to generate an instance of '%s'. The " + "input data was invalid for the allOf schema '%s' in the composed " + "schema '%s'. Error=%s" % ( + allof_class.__name__, + allof_class.__name__, + self.__class__.__name__, + str(ex) + ) + ), ex) + return composed_instances + + +def get_oneof_instance(self, model_args, constant_args): + """ + Find the oneOf schema that matches the input data (e.g. payload). + If exactly one schema matches the input data, an instance of that schema + is returned. + If zero or more than one schema match the input data, an exception is raised. + In OAS 3.x, the payload MUST, by validation, match exactly one of the + schemas described by oneOf. + Args: + self: the class we are handling + model_args (dict): var_name to var_value + The input data, e.g. the payload that must match a oneOf schema + in the OpenAPI document. + constant_args (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Returns + oneof_instance (instance) + """ + if len(self._composed_schemas['oneOf']) == 0: + return None + + oneof_instances = [] + # Iterate over each oneOf schema and determine if the input data + # matches the oneOf schemas. + for oneof_class in self._composed_schemas['oneOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if oneof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + # transform js keys from input data to python keys in fixed_model_args + fixed_model_args = change_keys_js_to_python( + model_args, oneof_class) + + # Extract a dict with the properties that are declared in the oneOf schema. + # Undeclared properties (e.g. properties that are allowed because of the + # additionalProperties attribute in the OAS document) are not added to + # the dict. + kwargs = {} + var_names = set(oneof_class.openapi_types.keys()) + for var_name in var_names: + if var_name in fixed_model_args: + kwargs[var_name] = fixed_model_args[var_name] + + # do not try to make a model with no input args + if len(kwargs) == 0: + continue + + # and use it to make the instance + kwargs.update(constant_args) + try: + oneof_instance = oneof_class(**kwargs) + oneof_instances.append(oneof_instance) + except Exception: + pass + if len(oneof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None " + "of the oneOf schemas matched the input data." % + self.__class__.__name__ + ) + elif len(oneof_instances) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Multiple " + "oneOf schemas matched the inputs, but a max of one is allowed." % + self.__class__.__name__ + ) + return oneof_instances[0] + + +def get_anyof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + The input data, e.g. the payload that must match at least one + anyOf child schema in the OpenAPI document. + constant_args (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Returns + anyof_instances (list) + """ + anyof_instances = [] + if len(self._composed_schemas['anyOf']) == 0: + return anyof_instances + + for anyof_class in self._composed_schemas['anyOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if anyof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + # transform js keys to python keys in fixed_model_args + fixed_model_args = change_keys_js_to_python(model_args, anyof_class) + + # extract a dict of only required keys from these_model_vars + kwargs = {} + var_names = set(anyof_class.openapi_types.keys()) + for var_name in var_names: + if var_name in fixed_model_args: + kwargs[var_name] = fixed_model_args[var_name] + + # do not try to make a model with no input args + if len(kwargs) == 0: + continue + + # and use it to make the instance + kwargs.update(constant_args) + try: + anyof_instance = anyof_class(**kwargs) + anyof_instances.append(anyof_instance) + except Exception: + pass + if len(anyof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None of the " + "anyOf schemas matched the inputs." % + self.__class__.__name__ + ) + return anyof_instances + + +def get_additional_properties_model_instances( + composed_instances, self): + additional_properties_model_instances = [] + all_instances = [self] + all_instances.extend(composed_instances) + for instance in all_instances: + if instance.additional_properties_type is not None: + additional_properties_model_instances.append(instance) + return additional_properties_model_instances + + +def get_var_name_to_model_instances(self, composed_instances): + var_name_to_model_instances = {} + all_instances = [self] + all_instances.extend(composed_instances) + for instance in all_instances: + for var_name in instance.openapi_types: + if var_name not in var_name_to_model_instances: + var_name_to_model_instances[var_name] = [instance] + else: + var_name_to_model_instances[var_name].append(instance) + return var_name_to_model_instances + + +def get_unused_args(self, composed_instances, model_args): + unused_args = dict(model_args) + # arguments apssed to self were already converted to python names + # before __init__ was called + for var_name_py in self.attribute_map: + if var_name_py in unused_args: + del unused_args[var_name_py] + for instance in composed_instances: + if instance.__class__ in self._composed_schemas['allOf']: + for var_name_py in instance.attribute_map: + if var_name_py in unused_args: + del unused_args[var_name_py] + else: + for var_name_js in instance.attribute_map.values(): + if var_name_js in unused_args: + del unused_args[var_name_js] + return unused_args + + +def validate_get_composed_info(constant_args, model_args, self): + """ + For composed schemas, generate schema instances for + all schemas in the oneOf/anyOf/allOf definition. If additional + properties are allowed, also assign those properties on + all matched schemas that contain additionalProperties. + Openapi schemas are python classes. + + Exceptions are raised if: + - 0 or > 1 oneOf schema matches the model_args input data + - no anyOf schema matches the model_args input data + - any of the allOf schemas do not match the model_args input data + + Args: + constant_args (dict): these are the args that every model requires + model_args (dict): these are the required and optional spec args that + were passed in to make this model + self (class): the class that we are instantiating + This class contains self._composed_schemas + + Returns: + composed_info (list): length three + composed_instances (list): the composed instances which are not + self + var_name_to_model_instances (dict): a dict going from var_name + to the model_instance which holds that var_name + the model_instance may be self or an instance of one of the + classes in self.composed_instances() + additional_properties_model_instances (list): a list of the + model instances which have the property + additional_properties_type. This list can include self + """ + # create composed_instances + composed_instances = [] + allof_instances = get_allof_instances(self, model_args, constant_args) + composed_instances.extend(allof_instances) + oneof_instance = get_oneof_instance(self, model_args, constant_args) + if oneof_instance is not None: + composed_instances.append(oneof_instance) + anyof_instances = get_anyof_instances(self, model_args, constant_args) + composed_instances.extend(anyof_instances) + + # map variable names to composed_instances + var_name_to_model_instances = get_var_name_to_model_instances( + self, composed_instances) + + # set additional_properties_model_instances + additional_properties_model_instances = ( + get_additional_properties_model_instances(composed_instances, self) + ) + + # set any remaining values + unused_args = get_unused_args(self, composed_instances, model_args) + if len(unused_args) > 0 and \ + len(additional_properties_model_instances) == 0 and \ + (self._configuration is None or + not self._configuration.discard_unknown_keys): + raise ApiValueError( + "Invalid input arguments input when making an instance of " + "class %s. Not all inputs were used. The unused input data " + "is %s" % (self.__class__.__name__, unused_args) + ) + + # no need to add additional_properties to var_name_to_model_instances here + # because additional_properties_model_instances will direct us to that + # instance when we use getattr or setattr + # and we update var_name_to_model_instances in setattr + + return [ + composed_instances, + var_name_to_model_instances, + additional_properties_model_instances, + unused_args + ] diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/models/__init__.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/models/__init__.py new file mode 100644 index 000000000000..0cb2976e7c10 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/models/__init__.py @@ -0,0 +1,13 @@ +# coding: utf-8 + +# flake8: noqa + +# import all models into this package +# if you have many models here with many references from one model to another this may +# raise a RecursionError +# to avoid this, import only the models that you directly need like: +# from from dynamic_servers.model.pet import Pet +# or import this package, but before doing it, use: +# import sys +# sys.setrecursionlimit(n) + diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/rest.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/rest.py new file mode 100644 index 000000000000..e9bd23610fe3 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/rest.py @@ -0,0 +1,291 @@ +# coding: utf-8 + +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import io +import json +import logging +import re +import ssl + +import certifi +# python 2 and python 3 compatibility library +import six +from six.moves.urllib.parse import urlencode +import urllib3 + +from dynamic_servers.exceptions import ApiException, ApiValueError + + +logger = logging.getLogger(__name__) + + +class RESTResponse(io.IOBase): + + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.urllib3_response.getheaders() + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.urllib3_response.getheader(name, default) + + +class RESTClientObject(object): + + def __init__(self, configuration, pools_size=4, maxsize=None): + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + # ca_certs + if configuration.ssl_ca_cert: + ca_certs = configuration.ssl_ca_cert + else: + # if not set certificate file, use Mozilla's root certificates. + ca_certs = certifi.where() + + addition_pool_args = {} + if configuration.assert_hostname is not None: + addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 + + if configuration.retries is not None: + addition_pool_args['retries'] = configuration.retries + + if maxsize is None: + if configuration.connection_pool_maxsize is not None: + maxsize = configuration.connection_pool_maxsize + else: + maxsize = 4 + + # https pool manager + if configuration.proxy: + self.pool_manager = urllib3.ProxyManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=ca_certs, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, + **addition_pool_args + ) + else: + self.pool_manager = urllib3.PoolManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=ca_certs, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + **addition_pool_args + ) + + def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Perform requests. + + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, ) if six.PY3 else (int, long)): # noqa: E501,F821 + timeout = urllib3.Timeout(total=_request_timeout) + elif (isinstance(_request_timeout, tuple) and + len(_request_timeout) == 2): + timeout = urllib3.Timeout( + connect=_request_timeout[0], read=_request_timeout[1]) + + if 'Content-Type' not in headers: + headers['Content-Type'] = 'application/json' + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + if query_params: + url += '?' + urlencode(query_params) + if re.search('json', headers['Content-Type'], re.IGNORECASE): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=False, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=True, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + # Pass a `string` parameter directly in the body to support + # other content types than Json when `body` argument is + # provided in serialized form + elif isinstance(body, str) or isinstance(body, bytes): + request_body = body + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request(method, url, + fields=query_params, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + except urllib3.exceptions.SSLError as e: + msg = "{0}\n{1}".format(type(e).__name__, str(e)) + raise ApiException(status=0, reason=msg) + + if _preload_content: + r = RESTResponse(r) + + # log response body + logger.debug("response body: %s", r.data) + + if not 200 <= r.status <= 299: + raise ApiException(http_resp=r) + + return r + + def GET(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("GET", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("HEAD", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): + return self.request("DELETE", url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def POST(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("POST", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PUT", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def PATCH(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PATCH", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/git_push.sh b/samples/openapi3/client/features/dynamic-servers/python-experimental/git_push.sh new file mode 100644 index 000000000000..ced3be2b0c7b --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/requirements.txt b/samples/openapi3/client/features/dynamic-servers/python-experimental/requirements.txt new file mode 100644 index 000000000000..a56bedffbf57 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/requirements.txt @@ -0,0 +1,7 @@ +nulltype +certifi >= 14.05.14 +future; python_version<="2.7" +six >= 1.10 +python_dateutil >= 2.5.3 +setuptools >= 21.0.0 +urllib3 >= 1.15.1 diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/setup.cfg b/samples/openapi3/client/features/dynamic-servers/python-experimental/setup.cfg new file mode 100644 index 000000000000..11433ee875ab --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/setup.cfg @@ -0,0 +1,2 @@ +[flake8] +max-line-length=99 diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/setup.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/setup.py new file mode 100644 index 000000000000..5da7badc9768 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/setup.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from setuptools import setup, find_packages # noqa: H301 + +NAME = "dynamic-servers" +VERSION = "1.0.0" +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools + +REQUIRES = [ + "urllib3 >= 1.15", + "six >= 1.10", + "certifi", + "python-dateutil", + "nulltype", +] +EXTRAS = {':python_version <= "2.7"': ['future']} + +setup( + name=NAME, + version=VERSION, + description="OpenAPI Extension with dynamic servers", + author="OpenAPI Generator community", + author_email="team@openapitools.org", + url="", + keywords=["OpenAPI", "OpenAPI-Generator", "OpenAPI Extension with dynamic servers"], + install_requires=REQUIRES, + extras_require=EXTRAS, + packages=find_packages(exclude=["test", "tests"]), + include_package_data=True, + license="Apache-2.0", + long_description="""\ + This specification shows how to use dynamic servers. # noqa: E501 + """ +) diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/test-requirements.txt b/samples/openapi3/client/features/dynamic-servers/python-experimental/test-requirements.txt new file mode 100644 index 000000000000..06f7754d2044 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/test-requirements.txt @@ -0,0 +1,4 @@ +pytest~=4.6.7 # needed for python 2.7+3.4 +pytest-cov>=2.8.1 +pytest-randomly==1.2.3 # needed for python 2.7+3.4 +mock; python_version<="2.7" \ No newline at end of file diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/test/__init__.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/test/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/test/test_usage_api.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/test/test_usage_api.py new file mode 100644 index 000000000000..faffb9263dda --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/test/test_usage_api.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from __future__ import absolute_import + +import functools +import unittest + +import dynamic_servers +from dynamic_servers.api.usage_api import UsageApi # noqa: E501 + + +class TestUsageApi(unittest.TestCase): + """UsageApi unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_custom_server(self): + """Test case for custom_server + + Use custom server # noqa: E501 + """ + # expected value, config + servers = ( + ("https://custom-petstore.swagger.io:8080/v2/custom", {}), + ( + "https://custom-petstore.swagger.io:80/v2/custom", + { + "server_index": 0, + "server_variables": {"port": "80"}, # global override + }, + ), + ( + "https://custom-petstore.swagger.io:8080/v2/custom", + { + "server_index": 0, + "server_variables": {"port": "80"}, + "server_operation_variables": {"custom_server": {"port": "8080"}}, # operation override + }, + ), + ( + "https://third.example.com/global-prefix/custom", + { + "server_index": 2, + "server_variables": {"prefix": "global-prefix"}, # global override + }, + ), + ( + "https://third.example.com/local-prefix/custom", + { + "server_index": 1, + "server_variables": {"prefix": "global-prefix"}, + "server_operation_index": {"custom_server": 2}, + "server_operation_variables": {"custom_server": {"prefix": "local-prefix"}}, # operation override + }, + ), + ) + + def request(expected_url, method, url, **kwargs): + assert expected_url == url + raise RuntimeError("pass") + + for expected_url, kwargs in servers: + client = dynamic_servers.ApiClient(dynamic_servers.Configuration(**kwargs)) + client.request = functools.partial(request, expected_url) + api = UsageApi(client) + + try: + api.custom_server() + except RuntimeError as e: + assert "pass" == str(e) + + def test_default_server(self): + """Test case for default_server + + Use default server # noqa: E501 + """ + # expected value, config + servers = ( + ("http://petstore.swagger.io:80/v2/default", {}), + ( + "http://dev-petstore.swagger.io:8080/v2/default", + { + "server_index": 0, + "server_variables": {"server": "dev-petstore", "port": "8080"}, + }, + ), + ("https://localhost:8080/v1/default", {"server_index": 1}), + ( + "https://localhost:8080/v3/default", + {"server_index": 1, "server_variables": {"version": "v3"}}, + ), + ) + + def request(expected_url, method, url, **kwargs): + assert expected_url == url + raise RuntimeError("pass") + + for expected_url, kwargs in servers: + client = dynamic_servers.ApiClient(dynamic_servers.Configuration(**kwargs)) + client.request = functools.partial(request, expected_url) + api = UsageApi(client) + + try: + api.default_server() + except RuntimeError as e: + assert "pass" == str(e) + + +if __name__ == "__main__": + unittest.main() diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/tox.ini b/samples/openapi3/client/features/dynamic-servers/python-experimental/tox.ini new file mode 100644 index 000000000000..85712433c51c --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/tox.ini @@ -0,0 +1,9 @@ +[tox] +envlist = py27, py3 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + pytest --cov=dynamic_servers From 1d190976bcbcecfee5de97afab55a8e996d48a06 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Fri, 12 Jun 2020 14:37:44 +0200 Subject: [PATCH 15/18] regenerated --- .../x_auth_id_alias/api/usage_api.py | 44 +++++++++++-------- .../x_auth_id_alias/configuration.py | 35 ++++++++++++--- .../.openapi-generator/FILES | 2 - .../dynamic_servers/configuration.py | 5 ++- .../python/petstore_api/configuration.py | 8 ++-- 5 files changed, 63 insertions(+), 31 deletions(-) diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/api/usage_api.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/api/usage_api.py index 06a4ccfba181..7c509fe779e8 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/api/usage_api.py +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/api/usage_api.py @@ -78,9 +78,9 @@ def __any_key( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -106,7 +106,7 @@ def __any_key( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.any_key = Endpoint( @@ -119,7 +119,7 @@ def __any_key( 'endpoint_path': '/any', 'operation_id': 'any_key', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -186,9 +186,9 @@ def __both_keys( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -214,7 +214,7 @@ def __both_keys( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.both_keys = Endpoint( @@ -227,7 +227,7 @@ def __both_keys( 'endpoint_path': '/both', 'operation_id': 'both_keys', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -294,9 +294,9 @@ def __key_in_header( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -322,7 +322,7 @@ def __key_in_header( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.key_in_header = Endpoint( @@ -334,7 +334,7 @@ def __key_in_header( 'endpoint_path': '/header', 'operation_id': 'key_in_header', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -401,9 +401,9 @@ def __key_in_query( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -429,7 +429,7 @@ def __key_in_query( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.key_in_query = Endpoint( @@ -441,7 +441,7 @@ def __key_in_query( 'endpoint_path': '/query', 'operation_id': 'key_in_query', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ @@ -532,7 +532,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -631,7 +631,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'], self.api_client.configuration.server_variables + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/configuration.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/configuration.py index f86db086690a..53ebab0b4423 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/configuration.py +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/configuration.py @@ -94,17 +94,27 @@ class Configuration(object): _default = None - def __init__(self, host="http://petstore.swagger.io:80/v2", + def __init__(self, host=None, api_key=None, api_key_prefix=None, username=None, password=None, discard_unknown_keys=False, disabled_client_side_validations="", + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, ): """Constructor """ - self.host = host + self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host """Default Base url """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ self.temp_folder_path = None """Temp file folder for downloading files """ @@ -442,14 +452,18 @@ def get_host_settings(self): } ] - def get_host_from_settings(self, index, variables=None): + def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None :return: URL based on host settings """ + if index is None: + return self._base_path + variables = {} if variables is None else variables - servers = self.get_host_settings() + servers = self.get_host_settings() if servers is None else servers try: server = servers[index] @@ -461,7 +475,7 @@ def get_host_from_settings(self, index, variables=None): url = server['url'] # go through variables and replace placeholders - for variable_name, variable in server['variables'].items(): + for variable_name, variable in server.get('variables', {}).items(): used_value = variables.get( variable_name, variable['default_value']) @@ -476,3 +490,14 @@ def get_host_from_settings(self, index, variables=None): url = url.replace("{" + variable_name + "}", used_value) return url + + @property + def host(self): + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/FILES b/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/FILES index 16d0dedd8a10..e9b184541660 100644 --- a/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/FILES +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/.openapi-generator/FILES @@ -1,6 +1,5 @@ .gitignore .gitlab-ci.yml -.openapi-generator-ignore .travis.yml README.md docs/UsageApi.md @@ -21,5 +20,4 @@ setup.cfg setup.py test-requirements.txt test/__init__.py -test/test_usage_api.py tox.ini diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py index 38a3be5c1f4a..08bf360e20b6 100644 --- a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py @@ -316,15 +316,16 @@ def logger_format(self, value): self.__logger_format = value self.logger_formatter = logging.Formatter(self.__logger_format) - def get_api_key_with_prefix(self, identifier): + def get_api_key_with_prefix(self, identifier, alias=None): """Gets API key (with prefix if set). :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. :return: The token for api key authentication. """ if self.refresh_api_key_hook is not None: self.refresh_api_key_hook(self) - key = self.api_key.get(identifier) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) if key: prefix = self.api_key_prefix.get(identifier) if prefix: diff --git a/samples/openapi3/client/petstore/python/petstore_api/configuration.py b/samples/openapi3/client/petstore/python/petstore_api/configuration.py index d403a34e8d30..f434138bc84d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python/petstore_api/configuration.py @@ -554,9 +554,12 @@ def get_host_from_settings(self, index, variables=None, servers=None): """Gets host URL based on the index and variables :param index: array index of the host settings :param variables: hash of variable and the corresponding value - :param servers: host settings for the endpoint + :param servers: an array of host settings or None :return: URL based on host settings """ + if index is None: + return self._base_path + variables = {} if variables is None else variables servers = self.get_host_settings() if servers is None else servers @@ -589,9 +592,6 @@ def get_host_from_settings(self, index, variables=None, servers=None): @property def host(self): """Return generated host.""" - if self.server_index is None: - return self._base_path - return self.get_host_from_settings(self.server_index, variables=self.server_variables) @host.setter From ff976a4273b7221ea6f52f1a57be8da89961be75 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Sun, 14 Jun 2020 18:43:02 +0200 Subject: [PATCH 16/18] add docstring --- .../src/main/resources/python/configuration.mustache | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/modules/openapi-generator/src/main/resources/python/configuration.mustache b/modules/openapi-generator/src/main/resources/python/configuration.mustache index e549f8222fec..6afe91d02744 100644 --- a/modules/openapi-generator/src/main/resources/python/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/python/configuration.mustache @@ -67,6 +67,15 @@ class Configuration(object): :param signing_info: Configuration parameters for the HTTP signature security scheme. Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration {{/hasHttpSignatureMethods}} + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. {{#hasAuthMethods}} :Example: From 3706f4d89fc69f3a9d7969940e5d5dc0b8535dad Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Mon, 15 Jun 2020 10:27:18 +0200 Subject: [PATCH 17/18] regenerated --- .../python-asyncio/petstore_api/configuration.py | 9 +++++++++ .../python-experimental/petstore_api/configuration.py | 9 +++++++++ .../python-tornado/petstore_api/configuration.py | 9 +++++++++ .../client/petstore/python/petstore_api/configuration.py | 9 +++++++++ .../python-experimental/x_auth_id_alias/configuration.py | 9 +++++++++ .../python-experimental/dynamic_servers/configuration.py | 9 +++++++++ .../python-experimental/petstore_api/api/fake_api.py | 8 ++++---- .../python-experimental/petstore_api/configuration.py | 9 +++++++++ .../client/petstore/python/petstore_api/configuration.py | 9 +++++++++ 9 files changed, 76 insertions(+), 4 deletions(-) diff --git a/samples/client/petstore/python-asyncio/petstore_api/configuration.py b/samples/client/petstore/python-asyncio/petstore_api/configuration.py index b2b7351366aa..65676a6dccf6 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/configuration.py +++ b/samples/client/petstore/python-asyncio/petstore_api/configuration.py @@ -68,6 +68,15 @@ class Configuration(object): disabled. This can be useful to troubleshoot data validation problem, such as when the OpenAPI document validation rules do not match the actual API data received by the server. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. :Example: diff --git a/samples/client/petstore/python-experimental/petstore_api/configuration.py b/samples/client/petstore/python-experimental/petstore_api/configuration.py index 18bfbaf57fc4..88d9d50203f0 100644 --- a/samples/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/client/petstore/python-experimental/petstore_api/configuration.py @@ -69,6 +69,15 @@ class Configuration(object): disabled. This can be useful to troubleshoot data validation problem, such as when the OpenAPI document validation rules do not match the actual API data received by the server. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. :Example: diff --git a/samples/client/petstore/python-tornado/petstore_api/configuration.py b/samples/client/petstore/python-tornado/petstore_api/configuration.py index 18bfbaf57fc4..88d9d50203f0 100644 --- a/samples/client/petstore/python-tornado/petstore_api/configuration.py +++ b/samples/client/petstore/python-tornado/petstore_api/configuration.py @@ -69,6 +69,15 @@ class Configuration(object): disabled. This can be useful to troubleshoot data validation problem, such as when the OpenAPI document validation rules do not match the actual API data received by the server. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. :Example: diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python/petstore_api/configuration.py index 18bfbaf57fc4..88d9d50203f0 100644 --- a/samples/client/petstore/python/petstore_api/configuration.py +++ b/samples/client/petstore/python/petstore_api/configuration.py @@ -69,6 +69,15 @@ class Configuration(object): disabled. This can be useful to troubleshoot data validation problem, such as when the OpenAPI document validation rules do not match the actual API data received by the server. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. :Example: diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/configuration.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/configuration.py index 53ebab0b4423..40ce7239f9a7 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/configuration.py +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/configuration.py @@ -69,6 +69,15 @@ class Configuration(object): disabled. This can be useful to troubleshoot data validation problem, such as when the OpenAPI document validation rules do not match the actual API data received by the server. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. :Example: diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py index 08bf360e20b6..e04af8a0bd83 100644 --- a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/configuration.py @@ -69,6 +69,15 @@ class Configuration(object): disabled. This can be useful to troubleshoot data validation problem, such as when the OpenAPI document validation rules do not match the actual API data received by the server. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. """ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py index 0c369cddc27d..aef504479821 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py @@ -636,9 +636,9 @@ def __get_additional_properties_with_array_of_enums( _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. - _host_index (int): specifies the index of the server + _host_index (int/None): specifies the index of the server that we want to use. - Default is 0. + Default is read from the configuration. async_req (bool): execute request asynchronously Returns: @@ -664,7 +664,7 @@ def __get_additional_properties_with_array_of_enums( kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) - kwargs['_host_index'] = kwargs.get('_host_index', 0) + kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) self.get_additional_properties_with_array_of_enums = Endpoint( @@ -674,7 +674,7 @@ def __get_additional_properties_with_array_of_enums( 'endpoint_path': '/fake/additional-properties-with-array-of-enums', 'operation_id': 'get_additional_properties_with_array_of_enums', 'http_method': 'GET', - 'servers': [], + 'servers': None, }, params_map={ 'all': [ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py index f434138bc84d..c22e74e575f1 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py @@ -71,6 +71,15 @@ class Configuration(object): received by the server. :param signing_info: Configuration parameters for the HTTP signature security scheme. Must be an instance of petstore_api.signing.HttpSigningConfiguration + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. :Example: diff --git a/samples/openapi3/client/petstore/python/petstore_api/configuration.py b/samples/openapi3/client/petstore/python/petstore_api/configuration.py index f434138bc84d..c22e74e575f1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python/petstore_api/configuration.py @@ -71,6 +71,15 @@ class Configuration(object): received by the server. :param signing_info: Configuration parameters for the HTTP signature security scheme. Must be an instance of petstore_api.signing.HttpSigningConfiguration + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. :Example: From 66df64717c47d2e27ea2d2c6a57957c295496e58 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Tue, 23 Jun 2020 12:16:50 +0200 Subject: [PATCH 18/18] Fix wrong merge resolution --- .../python/python-experimental/api_client.mustache | 12 ++++++++++-- .../python-experimental/petstore_api/api_client.py | 12 ++++++++++-- .../x_auth_id_alias/api_client.py | 12 ++++++++++-- .../dynamic_servers/api_client.py | 12 ++++++++++-- .../python-experimental/petstore_api/api_client.py | 12 ++++++++++-- 5 files changed, 50 insertions(+), 10 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/api_client.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/api_client.mustache index da5dbfb3419e..d3b0b6f60e97 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/api_client.mustache @@ -656,7 +656,7 @@ class Endpoint(object): self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -755,7 +755,15 @@ class Endpoint(object): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'], self.api_client.configuration.server_variables + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/client/petstore/python-experimental/petstore_api/api_client.py b/samples/client/petstore/python-experimental/petstore_api/api_client.py index 114a08f4b796..891d42be49f3 100644 --- a/samples/client/petstore/python-experimental/petstore_api/api_client.py +++ b/samples/client/petstore/python-experimental/petstore_api/api_client.py @@ -635,7 +635,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -734,7 +734,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'], self.api_client.configuration.server_variables + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/api_client.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/api_client.py index bcc6e80fe072..d2559726f6d1 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/api_client.py +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/x_auth_id_alias/api_client.py @@ -635,7 +635,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -734,7 +734,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'], self.api_client.configuration.server_variables + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api_client.py b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api_client.py index efa8a2107628..ca8d70ce9a53 100644 --- a/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api_client.py +++ b/samples/openapi3/client/features/dynamic-servers/python-experimental/dynamic_servers/api_client.py @@ -635,7 +635,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -734,7 +734,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'], self.api_client.configuration.server_variables + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError( diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api_client.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api_client.py index 6136bfec1353..9f3a16a6691f 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api_client.py @@ -642,7 +642,7 @@ def __init__(self, settings=None, params_map=None, root_map=None, self.openapi_types = root_map['openapi_types'] extra_types = { 'async_req': (bool,), - '_host_index': (int,), + '_host_index': (none_type, int), '_preload_content': (bool,), '_request_timeout': (none_type, int, (int,), [int]), '_return_http_data_only': (bool,), @@ -741,7 +741,15 @@ def __call__(self, *args, **kwargs): def call_with_http_info(self, **kwargs): try: - _host = self.settings['servers'][kwargs['_host_index']] + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'], self.api_client.configuration.server_variables + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) except IndexError: if self.settings['servers']: raise ApiValueError(