19
19
from models import *
20
20
21
21
22
- class ApiClient :
22
+ class ApiClient ( object ) :
23
23
"""Generic API client for Swagger client library builds
24
24
25
25
Attributes:
@@ -41,22 +41,22 @@ def callAPI(self, resourcePath, method, queryParams, postData,
41
41
headers = {}
42
42
if headerParams :
43
43
for param , value in headerParams .iteritems ():
44
- headers [param ] = value
44
+ headers [param ] = ApiClient . sanitizeForSerialization ( value )
45
45
46
46
if self .headerName :
47
- headers [self .headerName ] = self .headerValue
47
+ headers [self .headerName ] = ApiClient . sanitizeForSerialization ( self .headerValue )
48
48
49
49
if self .cookie :
50
- headers ['Cookie' ] = self .cookie
50
+ headers ['Cookie' ] = ApiClient . sanitizeForSerialization ( self .cookie )
51
51
52
52
data = None
53
53
54
54
if queryParams :
55
55
# Need to remove None values, these should not be sent
56
56
sentQueryParams = {}
57
57
for param , value in queryParams .items ():
58
- if value != None :
59
- sentQueryParams [param ] = value
58
+ if value is not None :
59
+ sentQueryParams [param ] = ApiClient . sanitizeForSerialization ( value )
60
60
url = url + '?' + urllib .urlencode (sentQueryParams )
61
61
62
62
if method in ['GET' ]:
@@ -65,7 +65,7 @@ def callAPI(self, resourcePath, method, queryParams, postData,
65
65
66
66
elif method in ['POST' , 'PUT' , 'DELETE' ]:
67
67
if postData :
68
- postData = self .sanitizeForSerialization (postData )
68
+ postData = ApiClient .sanitizeForSerialization (postData )
69
69
if 'Content-type' not in headers :
70
70
headers ['Content-type' ] = 'application/json'
71
71
data = json .dumps (postData )
@@ -107,34 +107,38 @@ def toPathValue(self, obj):
107
107
else :
108
108
return urllib .quote (str (obj ))
109
109
110
- def sanitizeForSerialization (self , obj ):
111
- """Dump an object into JSON for POSTing."""
112
-
113
- if type (obj ) == type (None ):
110
+ @staticmethod
111
+ def sanitizeForSerialization (obj ):
112
+ """
113
+ Sanitize an object for Request.
114
+
115
+ If obj is None, return None.
116
+ If obj is str, int, long, float, bool, return directly.
117
+ If obj is datetime.datetime, datetime.date convert to string in iso8601 format.
118
+ If obj is list, santize each element in the list.
119
+ If obj is dict, return the dict.
120
+ If obj is swagger model, return the properties dict.
121
+ """
122
+ if isinstance (obj , type (None )):
114
123
return None
115
- elif type (obj ) in [ str , int , long , float , bool ] :
124
+ elif isinstance (obj , ( str , int , long , float , bool , file )) :
116
125
return obj
117
- elif type (obj ) == list :
118
- return [self .sanitizeForSerialization (subObj ) for subObj in obj ]
119
- elif type (obj ) == datetime .datetime :
126
+ elif isinstance (obj , list ) :
127
+ return [ApiClient .sanitizeForSerialization (subObj ) for subObj in obj ]
128
+ elif isinstance (obj , ( datetime .datetime , datetime . date )) :
120
129
return obj .isoformat ()
121
130
else :
122
- if type (obj ) == dict :
131
+ if isinstance (obj , dict ) :
123
132
objDict = obj
124
133
else :
125
- objDict = obj .__dict__
126
- return {key : self .sanitizeForSerialization (val )
127
- for (key , val ) in objDict .iteritems ()
128
- if key != 'swaggerTypes' }
129
-
130
- if type (postData ) == list :
131
- # Could be a list of objects
132
- if type (postData [0 ]) in safeToDump :
133
- data = json .dumps (postData )
134
- else :
135
- data = json .dumps ([datum .__dict__ for datum in postData ])
136
- elif type (postData ) not in safeToDump :
137
- data = json .dumps (postData .__dict__ )
134
+ # Convert model obj to dict except attributes `swaggerTypes`, `attributeMap`
135
+ # and attributes which value is not None.
136
+ # Convert attribute name to json key in model definition for request.
137
+ objDict = {obj .attributeMap [key ]: val
138
+ for key , val in obj .__dict__ .iteritems ()
139
+ if key != 'swaggerTypes' and key != 'attributeMap' and val is not None }
140
+ return {key : ApiClient .sanitizeForSerialization (val )
141
+ for (key , val ) in objDict .iteritems ()}
138
142
139
143
def buildMultipartFormData (self , postData , files ):
140
144
def escape_quotes (s ):
@@ -194,16 +198,13 @@ def deserialize(self, obj, objClass):
194
198
if objClass in [int , long , float , dict , list , str , bool ]:
195
199
return objClass (obj )
196
200
elif objClass == datetime :
197
- # Server will always return a time stamp in UTC, but with
198
- # trailing +0000 indicating no offset from UTC. So don't process
199
- # last 5 characters.
200
- return datetime .datetime .strptime (obj [:- 5 ], "%Y-%m-%dT%H:%M:%S.%f" )
201
+ return self .__parse_string_to_datetime (obj )
201
202
202
203
instance = objClass ()
203
204
204
205
for attr , attrType in instance .swaggerTypes .iteritems ():
205
- if obj is not None and attr in obj and type (obj ) in [list , dict ]:
206
- value = obj [attr ]
206
+ if obj is not None and instance . attributeMap [ attr ] in obj and type (obj ) in [list , dict ]:
207
+ value = obj [instance . attributeMap [ attr ] ]
207
208
if attrType in ['str' , 'int' , 'long' , 'float' , 'bool' ]:
208
209
attrType = eval (attrType )
209
210
try :
@@ -214,7 +215,7 @@ def deserialize(self, obj, objClass):
214
215
value = value
215
216
setattr (instance , attr , value )
216
217
elif (attrType == 'datetime' ):
217
- setattr (instance , attr , datetime . datetime . strptime (value [: - 5 ], "%Y-%m-%dT%H:%M:%S.%f" ))
218
+ setattr (instance , attr , self . __parse_string_to_datetime (value ))
218
219
elif 'list[' in attrType :
219
220
match = re .match ('list\[(.*)\]' , attrType )
220
221
subClass = match .group (1 )
@@ -226,10 +227,21 @@ def deserialize(self, obj, objClass):
226
227
subValues .append (self .deserialize (subValue , subClass ))
227
228
setattr (instance , attr , subValues )
228
229
else :
229
- setattr (instance , attr , self .deserialize (value , objClass ))
230
+ setattr (instance , attr , self .deserialize (value , attrType ))
230
231
231
232
return instance
232
233
234
+ def __parse_string_to_datetime (self , string ):
235
+ """
236
+ Parse datetime in string to datetime.
237
+
238
+ The string should be in iso8601 datetime format.
239
+ """
240
+ try :
241
+ from dateutil .parser import parse
242
+ return parse (string )
243
+ except ImportError :
244
+ return string
233
245
234
246
class MethodRequest (urllib2 .Request ):
235
247
def __init__ (self , * args , ** kwargs ):
@@ -243,4 +255,4 @@ def __init__(self, *args, **kwargs):
243
255
return urllib2 .Request .__init__ (self , * args , ** kwargs )
244
256
245
257
def get_method (self ):
246
- return getattr (self , 'method' , urllib2 .Request .get_method (self ))
258
+ return getattr (self , 'method' , urllib2 .Request .get_method (self ))
0 commit comments