forked from loafle/openapi-generator-original
[Python] Make the code look Pythonic (#4352)
This commit is contained in:
@@ -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)
|
||||
|
||||
10
samples/client/petstore/python/docs/ClassModel.md
Normal file
10
samples/client/petstore/python/docs/ClassModel.md
Normal file
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 = {}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
42
samples/client/petstore/python/test/test_class_model.py
Normal file
42
samples/client/petstore/python/test/test_class_model.py
Normal file
@@ -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()
|
||||
Reference in New Issue
Block a user