diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 6b1a7d7e61b..eb8b73c7bdf 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -1,13 +1,7 @@ # coding: utf-8 - {{>partial_header}} - from __future__ import absolute_import -from . import models -from .rest import RESTClientObject -from .rest import ApiException - import os import re import json @@ -15,14 +9,15 @@ import mimetypes import tempfile import threading -from datetime import datetime -from datetime import date +from datetime import date, datetime # python 2 and python 3 compatibility library from six import PY3, integer_types, iteritems, text_type from six.moves.urllib.parse import quote +from . import models from .configuration import Configuration +from .rest import ApiException, RESTClientObject class ApiClient(object): @@ -42,8 +37,20 @@ class ApiClient(object): :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. """ - def __init__(self, host=None, header_name=None, header_value=None, cookie=None): + PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int if PY3 else long, + 'float': float, + 'str': str, + 'bool': bool, + 'date': date, + 'datetime': datetime, + 'object': object, + } + + def __init__(self, host=None, header_name=None, header_value=None, cookie=None): """ Constructor of the class. """ @@ -144,7 +151,10 @@ class ApiClient(object): return_data = None if callback: - callback(return_data) if _return_http_data_only else callback((return_data, response_data.status, response_data.getheaders())) + if _return_http_data_only: + callback(return_data) + else: + callback((return_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: return (return_data) else: @@ -165,10 +175,9 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) - if isinstance(obj, type(None)): + if obj is None: return None - elif isinstance(obj, types): + elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) @@ -178,21 +187,21 @@ class ApiClient(object): for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() - else: - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) - if getattr(obj, attr) is not None} - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `swagger_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in iteritems(obj.swagger_types) + if getattr(obj, attr) is not None} + + return {key: self.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} def deserialize(self, response, response_type): """ @@ -206,7 +215,7 @@ class ApiClient(object): """ # handle file downloading # save response body into a tmp file and return the instance - if "file" == response_type: + if response_type == "file": return self.__deserialize_file(response) # fetch data from response object @@ -241,17 +250,12 @@ class ApiClient(object): for k, v in iteritems(data)} # convert str to class - # for native types - if klass in ['int', 'float', 'str', 'bool', - "date", 'datetime', "object"]: - klass = eval(klass) - elif klass == 'long': - klass = int if PY3 else long - # for model types + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = eval('models.' + klass) + klass = getattr(models, klass) - if klass in integer_types or klass in (float, str, bool): + if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -451,7 +455,7 @@ class ApiClient(object): if not accepts: return - accepts = list(map(lambda x: x.lower(), accepts)) + accepts = [x.lower() for x in accepts] if 'application/json' in accepts: return 'application/json' @@ -468,7 +472,7 @@ class ApiClient(object): if not content_types: return 'application/json' - content_types = list(map(lambda x: x.lower(), content_types)) + content_types = [x.lower() for x in content_types] if 'application/json' in content_types or '*/*' in content_types: return 'application/json' @@ -538,12 +542,11 @@ class ApiClient(object): :return: int, long, float, str, bool. """ try: - value = klass(data) + return klass(data) except UnicodeEncodeError: - value = unicode(data) + return unicode(data) except TypeError: - value = data - return value + return data def __deserialize_object(self, value): """ @@ -568,8 +571,7 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a date object" - .format(string) + reason="Failed to parse `{0}` into a date object".format(string) ) def __deserialize_datatime(self, string): @@ -589,8 +591,10 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a datetime object". - format(string) + reason=( + "Failed to parse `{0}` into a datetime object" + .format(string) + ) ) def __deserialize_model(self, data, klass): @@ -608,7 +612,7 @@ class ApiClient(object): for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ - and instance.attribute_map[attr] in data\ + and instance.attribute_map[attr] in data \ and isinstance(data, (list, dict)): value = data[instance.attribute_map[attr]] setattr(instance, attr, self.__deserialize(value, attr_type)) diff --git a/samples/client/petstore-security-test/python/petstore_api/__init__.py b/samples/client/petstore-security-test/python/petstore_api/__init__.py index 6bfb00016ef..a8cf9ed66eb 100644 --- a/samples/client/petstore-security-test/python/petstore_api/__init__.py +++ b/samples/client/petstore-security-test/python/petstore_api/__init__.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from __future__ import absolute_import # import models into sdk package diff --git a/samples/client/petstore-security-test/python/petstore_api/api_client.py b/samples/client/petstore-security-test/python/petstore_api/api_client.py index adf66173dbc..02c6172ccc4 100644 --- a/samples/client/petstore-security-test/python/petstore_api/api_client.py +++ b/samples/client/petstore-security-test/python/petstore_api/api_client.py @@ -1,29 +1,16 @@ # coding: utf-8 - """ -Copyright 2016 SmartBear Software + Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - ref: https://github.com/swagger-api/swagger-codegen + OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r + Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r + Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import -from . import models -from .rest import RESTClientObject -from .rest import ApiException - import os import re import json @@ -31,14 +18,15 @@ import mimetypes import tempfile import threading -from datetime import datetime -from datetime import date +from datetime import date, datetime # python 2 and python 3 compatibility library from six import PY3, integer_types, iteritems, text_type from six.moves.urllib.parse import quote +from . import models from .configuration import Configuration +from .rest import ApiException, RESTClientObject class ApiClient(object): @@ -58,8 +46,20 @@ class ApiClient(object): :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. """ - def __init__(self, host=None, header_name=None, header_value=None, cookie=None): + PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int if PY3 else long, + 'float': float, + 'str': str, + 'bool': bool, + 'date': date, + 'datetime': datetime, + 'object': object, + } + + def __init__(self, host=None, header_name=None, header_value=None, cookie=None): """ Constructor of the class. """ @@ -96,7 +96,8 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None): + _return_http_data_only=None, collection_formats=None, _preload_content=True, + _request_timeout=None): # header parameters header_params = header_params or {} @@ -144,22 +145,29 @@ class ApiClient(object): response_data = self.request(method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body) + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) self.last_response = response_data - # deserialize response data - if response_type: - deserialized_data = self.deserialize(response_data, response_type) - else: - deserialized_data = None + return_data = response_data + if _preload_content: + # deserialize response data + if response_type: + return_data = self.deserialize(response_data, response_type) + else: + return_data = None if callback: - callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders())) + if _return_http_data_only: + callback(return_data) + else: + callback((return_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: - return (deserialized_data) + return (return_data) else: - return (deserialized_data, response_data.status, response_data.getheaders()) + return (return_data, response_data.status, response_data.getheaders()) def sanitize_for_serialization(self, obj): """ @@ -176,34 +184,33 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) - if isinstance(obj, type(None)): + if obj is None: return None - elif isinstance(obj, types): + 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) + for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() - else: - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) - if getattr(obj, attr) is not None} - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `swagger_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in iteritems(obj.swagger_types) + if getattr(obj, attr) is not None} + + return {key: self.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} def deserialize(self, response, response_type): """ @@ -217,7 +224,7 @@ class ApiClient(object): """ # handle file downloading # save response body into a tmp file and return the instance - if "file" == response_type: + if response_type == "file": return self.__deserialize_file(response) # fetch data from response object @@ -252,17 +259,12 @@ class ApiClient(object): for k, v in iteritems(data)} # convert str to class - # for native types - if klass in ['int', 'float', 'str', 'bool', - "date", 'datetime', "object"]: - klass = eval(klass) - elif klass == 'long': - klass = int if PY3 else long - # for model types + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = eval('models.' + klass) + klass = getattr(models, klass) - if klass in integer_types or klass in (float, str, bool): + if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -277,7 +279,8 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None): + _return_http_data_only=None, collection_formats=None, _preload_content=True, + _request_timeout=None): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. @@ -301,6 +304,10 @@ class ApiClient(object): :param _return_http_data_only: response data without head status code and headers :param collection_formats: dict of collection formats for path, query, header, and post parameters. + :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. :return: If provide parameter callback, the request will be called asynchronously. @@ -313,7 +320,7 @@ class ApiClient(object): path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, callback, - _return_http_data_only, collection_formats) + _return_http_data_only, collection_formats, _preload_content, _request_timeout) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, @@ -322,51 +329,65 @@ class ApiClient(object): post_params, files, response_type, auth_settings, callback, _return_http_data_only, - collection_formats)) + collection_formats, _preload_content, _request_timeout)) thread.start() return thread def request(self, method, url, query_params=None, headers=None, - post_params=None, body=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 ValueError( @@ -443,7 +464,7 @@ class ApiClient(object): if not accepts: return - accepts = list(map(lambda x: x.lower(), accepts)) + accepts = [x.lower() for x in accepts] if 'application/json' in accepts: return 'application/json' @@ -460,9 +481,9 @@ class ApiClient(object): if not content_types: return 'application/json' - content_types = list(map(lambda x: x.lower(), content_types)) + content_types = [x.lower() for x in content_types] - if 'application/json' in content_types: + if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: return content_types[0] @@ -530,12 +551,11 @@ class ApiClient(object): :return: int, long, float, str, bool. """ try: - value = klass(data) + return klass(data) except UnicodeEncodeError: - value = unicode(data) + return unicode(data) except TypeError: - value = data - return value + return data def __deserialize_object(self, value): """ @@ -560,8 +580,7 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a date object" - .format(string) + reason="Failed to parse `{0}` into a date object".format(string) ) def __deserialize_datatime(self, string): @@ -581,8 +600,10 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a datetime object". - format(string) + reason=( + "Failed to parse `{0}` into a datetime object" + .format(string) + ) ) def __deserialize_model(self, data, klass): @@ -600,7 +621,7 @@ class ApiClient(object): for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ - and instance.attribute_map[attr] in data\ + and instance.attribute_map[attr] in data \ and isinstance(data, (list, dict)): value = data[instance.attribute_map[attr]] setattr(instance, attr, self.__deserialize(value, attr_type)) diff --git a/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py b/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py index b2a58f84e7b..f713d227c0e 100644 --- a/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from __future__ import absolute_import import sys @@ -54,8 +43,6 @@ class FakeApi(object): def test_code_inject____end__rn_n_r(self, **kwargs): """ To test code injection */ ' \" =end -- \\r\\n \\n \\r - - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -81,8 +68,6 @@ class FakeApi(object): def test_code_inject____end__rn_n_r_with_http_info(self, **kwargs): """ To test code injection */ ' \" =end -- \\r\\n \\n \\r - - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -102,6 +87,8 @@ class FakeApi(object): all_params = ['test_code_inject____end____rn_n_r'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -144,14 +131,16 @@ class FakeApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore-security-test/python/petstore_api/configuration.py b/samples/client/petstore-security-test/python/petstore_api/configuration.py index b612f103532..55b00220da5 100644 --- a/samples/client/petstore-security-test/python/petstore_api/configuration.py +++ b/samples/client/petstore-security-test/python/petstore_api/configuration.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from __future__ import absolute_import import urllib3 diff --git a/samples/client/petstore-security-test/python/petstore_api/models/__init__.py b/samples/client/petstore-security-test/python/petstore_api/models/__init__.py index d5006ee92c6..a75a00eb198 100644 --- a/samples/client/petstore-security-test/python/petstore_api/models/__init__.py +++ b/samples/client/petstore-security-test/python/petstore_api/models/__init__.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from __future__ import absolute_import # import models into model package diff --git a/samples/client/petstore-security-test/python/petstore_api/models/model_return.py b/samples/client/petstore-security-test/python/petstore_api/models/model_return.py index 886ec0d5601..8256e70ca94 100644 --- a/samples/client/petstore-security-test/python/petstore_api/models/model_return.py +++ b/samples/client/petstore-security-test/python/petstore_api/models/model_return.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from pprint import pformat from six import iteritems import re @@ -51,7 +40,6 @@ class ModelReturn(object): self.__return = _return - @property def _return(self): """ diff --git a/samples/client/petstore-security-test/python/petstore_api/rest.py b/samples/client/petstore-security-test/python/petstore_api/rest.py index fc6b878837c..2c54f4ceae8 100644 --- a/samples/client/petstore-security-test/python/petstore_api/rest.py +++ b/samples/client/petstore-security-test/python/petstore_api/rest.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from __future__ import absolute_import import io @@ -69,10 +58,11 @@ class RESTResponse(io.IOBase): class RESTClientObject(object): - def __init__(self, pools_size=4): + def __init__(self, pools_size=4, maxsize=4): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 + # maxsize is the number of requests to host that are allowed in parallel # ca_certs vs cert_file vs key_file # http://stackoverflow.com/a/23957365/2985775 @@ -98,6 +88,7 @@ class RESTClientObject(object): # https pool manager self.pool_manager = urllib3.PoolManager( num_pools=pools_size, + maxsize=maxsize, cert_reqs=cert_reqs, ca_certs=ca_certs, cert_file=cert_file, @@ -105,7 +96,7 @@ class RESTClientObject(object): ) def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None): + body=None, post_params=None, _preload_content=True, _request_timeout=None): """ :param method: http request method :param url: http request url @@ -115,6 +106,10 @@ class RESTClientObject(object): :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'] @@ -127,6 +122,13 @@ class RESTClientObject(object): post_params = post_params or {} headers = headers or {} + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, ) if PY3 else (int, long)): + 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' @@ -141,11 +143,15 @@ class RESTClientObject(object): 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': 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 @@ -154,6 +160,8 @@ class RESTClientObject(object): 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 @@ -162,6 +170,8 @@ class RESTClientObject(object): 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 @@ -172,68 +182,89 @@ class RESTClientObject(object): 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) - r = RESTResponse(r) + if _preload_content: + r = RESTResponse(r) - # In the python 3, the response.data is bytes. - # we need to decode it to string. - if PY3: - r.data = r.data.decode('utf8') + # In the python 3, the response.data is bytes. + # we need to decode it to string. + if PY3: + r.data = r.data.decode('utf8') - # log response body - logger.debug("response body: %s", r.data) + # log response body + logger.debug("response body: %s", r.data) if r.status not in range(200, 206): raise ApiException(http_resp=r) return r - def GET(self, url, headers=None, query_params=None): + 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): + 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): + 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): + 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): + 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): + 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): + 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/client/petstore-security-test/python/setup.py b/samples/client/petstore-security-test/python/setup.py index 21f9241b859..3f8f4c118e1 100644 --- a/samples/client/petstore-security-test/python/setup.py +++ b/samples/client/petstore-security-test/python/setup.py @@ -8,26 +8,14 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + import sys from setuptools import setup, find_packages NAME = "petstore_api" VERSION = "1.0.0" - # To install the library, run the following # # python setup.py install @@ -51,4 +39,3 @@ setup( This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- """ ) - diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 1c59d444ffc..fd16a182ca2 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -105,6 +105,7 @@ Class | Method | HTTP request | Description - [ArrayTest](docs/ArrayTest.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) + - [ClassModel](docs/ClassModel.md) - [Client](docs/Client.md) - [Dog](docs/Dog.md) - [EnumArrays](docs/EnumArrays.md) diff --git a/samples/client/petstore/python/docs/ClassModel.md b/samples/client/petstore/python/docs/ClassModel.md new file mode 100644 index 00000000000..7f6f6d17211 --- /dev/null +++ b/samples/client/petstore/python/docs/ClassModel.md @@ -0,0 +1,10 @@ +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index 69186f43a50..cad45b8f219 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -153,7 +153,7 @@ enum_header_string_array = ['enum_header_string_array_example'] # list[str] | He enum_header_string = '-efg' # str | Header parameter enum test (string) (optional) (default to -efg) enum_query_string_array = ['enum_query_string_array_example'] # list[str] | Query parameter enum test (string array) (optional) enum_query_string = '-efg' # str | Query parameter enum test (string) (optional) (default to -efg) -enum_query_integer = 3.4 # float | Query parameter enum test (double) (optional) +enum_query_integer = 56 # int | Query parameter enum test (double) (optional) enum_query_double = 1.2 # float | Query parameter enum test (double) (optional) try: @@ -173,7 +173,7 @@ Name | Type | Description | Notes **enum_header_string** | **str**| Header parameter enum test (string) | [optional] [default to -efg] **enum_query_string_array** | [**list[str]**](str.md)| Query parameter enum test (string array) | [optional] **enum_query_string** | **str**| Query parameter enum test (string) | [optional] [default to -efg] - **enum_query_integer** | **float**| Query parameter enum test (double) | [optional] + **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] **enum_query_double** | **float**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/python/petstore_api/__init__.py b/samples/client/petstore/python/petstore_api/__init__.py index 72c011b0f13..ad9f5a3e145 100644 --- a/samples/client/petstore/python/petstore_api/__init__.py +++ b/samples/client/petstore/python/petstore_api/__init__.py @@ -23,6 +23,7 @@ from .models.array_of_number_only import ArrayOfNumberOnly from .models.array_test import ArrayTest from .models.cat import Cat from .models.category import Category +from .models.class_model import ClassModel from .models.client import Client from .models.dog import Dog from .models.enum_arrays import EnumArrays diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index f5824c50572..d4a40cfcbfd 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -1,5 +1,4 @@ # coding: utf-8 - """ Swagger Petstore @@ -10,13 +9,8 @@ Generated by: https://github.com/swagger-api/swagger-codegen.git """ - from __future__ import absolute_import -from . import models -from .rest import RESTClientObject -from .rest import ApiException - import os import re import json @@ -24,14 +18,15 @@ import mimetypes import tempfile import threading -from datetime import datetime -from datetime import date +from datetime import date, datetime # python 2 and python 3 compatibility library from six import PY3, integer_types, iteritems, text_type from six.moves.urllib.parse import quote +from . import models from .configuration import Configuration +from .rest import ApiException, RESTClientObject class ApiClient(object): @@ -51,8 +46,20 @@ class ApiClient(object): :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. """ - def __init__(self, host=None, header_name=None, header_value=None, cookie=None): + PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int if PY3 else long, + 'float': float, + 'str': str, + 'bool': bool, + 'date': date, + 'datetime': datetime, + 'object': object, + } + + def __init__(self, host=None, header_name=None, header_value=None, cookie=None): """ Constructor of the class. """ @@ -153,7 +160,10 @@ class ApiClient(object): return_data = None if callback: - callback(return_data) if _return_http_data_only else callback((return_data, response_data.status, response_data.getheaders())) + if _return_http_data_only: + callback(return_data) + else: + callback((return_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: return (return_data) else: @@ -174,10 +184,9 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) - if isinstance(obj, type(None)): + if obj is None: return None - elif isinstance(obj, types): + elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) @@ -187,21 +196,21 @@ class ApiClient(object): for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() - else: - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) - if getattr(obj, attr) is not None} - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `swagger_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in iteritems(obj.swagger_types) + if getattr(obj, attr) is not None} + + return {key: self.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} def deserialize(self, response, response_type): """ @@ -215,7 +224,7 @@ class ApiClient(object): """ # handle file downloading # save response body into a tmp file and return the instance - if "file" == response_type: + if response_type == "file": return self.__deserialize_file(response) # fetch data from response object @@ -250,17 +259,12 @@ class ApiClient(object): for k, v in iteritems(data)} # convert str to class - # for native types - if klass in ['int', 'float', 'str', 'bool', - "date", 'datetime', "object"]: - klass = eval(klass) - elif klass == 'long': - klass = int if PY3 else long - # for model types + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = eval('models.' + klass) + klass = getattr(models, klass) - if klass in integer_types or klass in (float, str, bool): + if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -460,7 +464,7 @@ class ApiClient(object): if not accepts: return - accepts = list(map(lambda x: x.lower(), accepts)) + accepts = [x.lower() for x in accepts] if 'application/json' in accepts: return 'application/json' @@ -477,7 +481,7 @@ class ApiClient(object): if not content_types: return 'application/json' - content_types = list(map(lambda x: x.lower(), content_types)) + content_types = [x.lower() for x in content_types] if 'application/json' in content_types or '*/*' in content_types: return 'application/json' @@ -547,12 +551,11 @@ class ApiClient(object): :return: int, long, float, str, bool. """ try: - value = klass(data) + return klass(data) except UnicodeEncodeError: - value = unicode(data) + return unicode(data) except TypeError: - value = data - return value + return data def __deserialize_object(self, value): """ @@ -577,8 +580,7 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a date object" - .format(string) + reason="Failed to parse `{0}` into a date object".format(string) ) def __deserialize_datatime(self, string): @@ -598,8 +600,10 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a datetime object". - format(string) + reason=( + "Failed to parse `{0}` into a datetime object" + .format(string) + ) ) def __deserialize_model(self, data, klass): @@ -617,7 +621,7 @@ class ApiClient(object): for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ - and instance.attribute_map[attr] in data\ + and instance.attribute_map[attr] in data \ and isinstance(data, (list, dict)): value = data[instance.attribute_map[attr]] setattr(instance, attr, self.__deserialize(value, attr_type)) diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index 3da6777bb3a..31857574da7 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -258,14 +258,14 @@ class FakeApi(object): raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") if 'pattern_without_delimiter' in params and not re.search('^[A-Z].*', params['pattern_without_delimiter']): raise ValueError("Invalid value for parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`, must conform to the pattern `/^[A-Z].*/`") - if 'integer' in params and params['integer'] > 100.0: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100.0`") - if 'integer' in params and params['integer'] < 10.0: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10.0`") - if 'int32' in params and params['int32'] > 200.0: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200.0`") - if 'int32' in params and params['int32'] < 20.0: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20.0`") + if 'integer' in params and params['integer'] > 100: + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100`") + if 'integer' in params and params['integer'] < 10: + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10`") + if 'int32' in params and params['int32'] > 200: + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200`") + if 'int32' in params and params['int32'] < 20: + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20`") if 'float' in params and params['float'] > 987.6: raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `987.6`") if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): @@ -364,7 +364,7 @@ class FakeApi(object): :param str enum_header_string: Header parameter enum test (string) :param list[str] enum_query_string_array: Query parameter enum test (string array) :param str enum_query_string: Query parameter enum test (string) - :param float enum_query_integer: Query parameter enum test (double) + :param int enum_query_integer: Query parameter enum test (double) :param float enum_query_double: Query parameter enum test (double) :return: None If the method is called asynchronously, @@ -396,7 +396,7 @@ class FakeApi(object): :param str enum_header_string: Header parameter enum test (string) :param list[str] enum_query_string_array: Query parameter enum test (string array) :param str enum_query_string: Query parameter enum test (string) - :param float enum_query_integer: Query parameter enum test (double) + :param int enum_query_integer: Query parameter enum test (double) :param float enum_query_double: Query parameter enum test (double) :return: None If the method is called asynchronously, diff --git a/samples/client/petstore/python/petstore_api/apis/store_api.py b/samples/client/petstore/python/petstore_api/apis/store_api.py index 82a4eee9e35..1764a9172b0 100644 --- a/samples/client/petstore/python/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/apis/store_api.py @@ -319,10 +319,10 @@ class StoreApi(object): if ('order_id' not in params) or (params['order_id'] is None): raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") - if 'order_id' in params and params['order_id'] > 5.0: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5.0`") - if 'order_id' in params and params['order_id'] < 1.0: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1.0`") + if 'order_id' in params and params['order_id'] > 5: + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5`") + if 'order_id' in params and params['order_id'] < 1: + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1`") collection_formats = {} diff --git a/samples/client/petstore/python/petstore_api/models/__init__.py b/samples/client/petstore/python/petstore_api/models/__init__.py index e8a9a6a8d69..844bc150b72 100644 --- a/samples/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/client/petstore/python/petstore_api/models/__init__.py @@ -23,6 +23,7 @@ from .array_of_number_only import ArrayOfNumberOnly from .array_test import ArrayTest from .cat import Cat from .category import Category +from .class_model import ClassModel from .client import Client from .dog import Dog from .enum_arrays import EnumArrays diff --git a/samples/client/petstore/python/petstore_api/models/class_model.py b/samples/client/petstore/python/petstore_api/models/class_model.py new file mode 100644 index 00000000000..dd08406c04b --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/class_model.py @@ -0,0 +1,112 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +""" + + +from pprint import pformat +from six import iteritems +import re + + +class ClassModel(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, _class=None): + """ + ClassModel - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + '_class': 'str' + } + + self.attribute_map = { + '_class': '_class' + } + + self.__class = _class + + @property + def _class(self): + """ + Gets the _class of this ClassModel. + + :return: The _class of this ClassModel. + :rtype: str + """ + return self.__class + + @_class.setter + def _class(self, _class): + """ + Sets the _class of this ClassModel. + + :param _class: The _class of this ClassModel. + :type: str + """ + + self.__class = _class + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/format_test.py b/samples/client/petstore/python/petstore_api/models/format_test.py index dcefc1e036b..1223bb1ea99 100644 --- a/samples/client/petstore/python/petstore_api/models/format_test.py +++ b/samples/client/petstore/python/petstore_api/models/format_test.py @@ -94,10 +94,10 @@ class FormatTest(object): :param integer: The integer of this FormatTest. :type: int """ - if integer is not None and integer > 100.0: - raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100.0`") - if integer is not None and integer < 10.0: - raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10.0`") + if integer is not None and integer > 100: + raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100`") + if integer is not None and integer < 10: + raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10`") self._integer = integer @@ -119,10 +119,10 @@ class FormatTest(object): :param int32: The int32 of this FormatTest. :type: int """ - if int32 is not None and int32 > 200.0: - raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200.0`") - if int32 is not None and int32 < 20.0: - raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20.0`") + if int32 is not None and int32 > 200: + raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200`") + if int32 is not None and int32 < 20: + raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20`") self._int32 = int32 diff --git a/samples/client/petstore/python/test/test_class_model.py b/samples/client/petstore/python/test/test_class_model.py new file mode 100644 index 00000000000..e502152ee8b --- /dev/null +++ b/samples/client/petstore/python/test/test_class_model.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +""" + + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.class_model import ClassModel + + +class TestClassModel(unittest.TestCase): + """ ClassModel unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testClassModel(self): + """ + Test ClassModel + """ + model = petstore_api.models.class_model.ClassModel() + + +if __name__ == '__main__': + unittest.main()