[Python] Make the code look Pythonic (#4352)

This commit is contained in:
Vlad Frolov
2016-12-09 11:26:23 +02:00
committed by wing328
parent c3571b28a5
commit 4d2a13018b
20 changed files with 471 additions and 313 deletions

View File

@@ -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))