weheat 2025.1.14rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of weheat might be problematic. Click here for more details.

weheat/api_client.py ADDED
@@ -0,0 +1,766 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Weheat Backend
5
+
6
+ This is the backend for the Weheat project
7
+
8
+ The version of the OpenAPI document: v1
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+
15
+ import atexit
16
+ import datetime
17
+ from dateutil.parser import parse
18
+ import json
19
+ import mimetypes
20
+ from multiprocessing.pool import ThreadPool
21
+ import os
22
+ import re
23
+ import tempfile
24
+
25
+ from urllib.parse import quote
26
+
27
+ from weheat.configuration import Configuration
28
+ from weheat.api_response import ApiResponse
29
+ import weheat.models
30
+ from weheat import rest
31
+ from weheat.exceptions import ApiValueError, ApiException
32
+
33
+
34
+ class ApiClient:
35
+ """Generic API client for OpenAPI client library builds.
36
+
37
+ OpenAPI generic API client. This client handles the client-
38
+ server communication, and is invariant across implementations. Specifics of
39
+ the methods and models for each application are generated from the OpenAPI
40
+ templates.
41
+
42
+ :param configuration: .Configuration object for this client
43
+ :param header_name: a header to pass when making calls to the API.
44
+ :param header_value: a header value to pass when making calls to
45
+ the API.
46
+ :param cookie: a cookie to include in the header when making calls
47
+ to the API
48
+ :param pool_threads: The number of threads to use for async requests
49
+ to the API. More threads means more concurrent API requests.
50
+ """
51
+
52
+ PRIMITIVE_TYPES = (float, bool, bytes, str, int)
53
+ NATIVE_TYPES_MAPPING = {
54
+ 'int': int,
55
+ 'long': int, # TODO remove as only py3 is supported?
56
+ 'float': float,
57
+ 'str': str,
58
+ 'bool': bool,
59
+ 'date': datetime.date,
60
+ 'datetime': datetime.datetime,
61
+ 'object': object,
62
+ }
63
+ _pool = None
64
+
65
+ def __init__(self, configuration=None, header_name=None, header_value=None,
66
+ cookie=None, pool_threads=1) -> None:
67
+ # use default configuration if none is provided
68
+ if configuration is None:
69
+ configuration = Configuration.get_default()
70
+ self.configuration = configuration
71
+ self.pool_threads = pool_threads
72
+
73
+ self.rest_client = rest.RESTClientObject(configuration)
74
+ self.default_headers = {}
75
+ if header_name is not None:
76
+ self.default_headers[header_name] = header_value
77
+ self.cookie = cookie
78
+ # Set default User-Agent.
79
+ self.user_agent = 'OpenAPI-Generator/2024.07.08/python'
80
+ self.client_side_validation = configuration.client_side_validation
81
+
82
+ def __enter__(self):
83
+ return self
84
+
85
+ def __exit__(self, exc_type, exc_value, traceback):
86
+ self.close()
87
+
88
+ def close(self):
89
+ if self._pool:
90
+ self._pool.close()
91
+ self._pool.join()
92
+ self._pool = None
93
+ if hasattr(atexit, 'unregister'):
94
+ atexit.unregister(self.close)
95
+
96
+ @property
97
+ def pool(self):
98
+ """Create thread pool on first request
99
+ avoids instantiating unused threadpool for blocking clients.
100
+ """
101
+ if self._pool is None:
102
+ atexit.register(self.close)
103
+ self._pool = ThreadPool(self.pool_threads)
104
+ return self._pool
105
+
106
+ @property
107
+ def user_agent(self):
108
+ """User agent for this API client"""
109
+ return self.default_headers['User-Agent']
110
+
111
+ @user_agent.setter
112
+ def user_agent(self, value):
113
+ self.default_headers['User-Agent'] = value
114
+
115
+ def set_default_header(self, header_name, header_value):
116
+ self.default_headers[header_name] = header_value
117
+
118
+
119
+ _default = None
120
+
121
+ @classmethod
122
+ def get_default(cls):
123
+ """Return new instance of ApiClient.
124
+
125
+ This method returns newly created, based on default constructor,
126
+ object of ApiClient class or returns a copy of default
127
+ ApiClient.
128
+
129
+ :return: The ApiClient object.
130
+ """
131
+ if cls._default is None:
132
+ cls._default = ApiClient()
133
+ return cls._default
134
+
135
+ @classmethod
136
+ def set_default(cls, default):
137
+ """Set default instance of ApiClient.
138
+
139
+ It stores default ApiClient.
140
+
141
+ :param default: object of ApiClient.
142
+ """
143
+ cls._default = default
144
+
145
+ def __call_api(
146
+ self, resource_path, method, path_params=None,
147
+ query_params=None, header_params=None, body=None, post_params=None,
148
+ files=None, response_types_map=None, auth_settings=None,
149
+ _return_http_data_only=None, collection_formats=None,
150
+ _preload_content=True, _request_timeout=None, _host=None,
151
+ _request_auth=None):
152
+
153
+ config = self.configuration
154
+
155
+ # header parameters
156
+ header_params = header_params or {}
157
+ header_params.update(self.default_headers)
158
+ if self.cookie:
159
+ header_params['Cookie'] = self.cookie
160
+ if header_params:
161
+ header_params = self.sanitize_for_serialization(header_params)
162
+ header_params = dict(self.parameters_to_tuples(header_params,
163
+ collection_formats))
164
+
165
+ # path parameters
166
+ if path_params:
167
+ path_params = self.sanitize_for_serialization(path_params)
168
+ path_params = self.parameters_to_tuples(path_params,
169
+ collection_formats)
170
+ for k, v in path_params:
171
+ # specified safe chars, encode everything
172
+ resource_path = resource_path.replace(
173
+ '{%s}' % k,
174
+ quote(str(v), safe=config.safe_chars_for_path_param)
175
+ )
176
+
177
+ # post parameters
178
+ if post_params or files:
179
+ post_params = post_params if post_params else []
180
+ post_params = self.sanitize_for_serialization(post_params)
181
+ post_params = self.parameters_to_tuples(post_params,
182
+ collection_formats)
183
+ post_params.extend(self.files_parameters(files))
184
+
185
+ # auth setting
186
+ self.update_params_for_auth(
187
+ header_params, query_params, auth_settings,
188
+ resource_path, method, body,
189
+ request_auth=_request_auth)
190
+
191
+ # body
192
+ if body:
193
+ body = self.sanitize_for_serialization(body)
194
+
195
+ # request url
196
+ if _host is None:
197
+ url = self.configuration.host + resource_path
198
+ else:
199
+ # use server/host defined in path or operation instead
200
+ url = _host + resource_path
201
+
202
+ # query parameters
203
+ if query_params:
204
+ query_params = self.sanitize_for_serialization(query_params)
205
+ url_query = self.parameters_to_url_query(query_params,
206
+ collection_formats)
207
+ url += "?" + url_query
208
+
209
+ try:
210
+ # perform request and return response
211
+ response_data = self.request(
212
+ method, url,
213
+ query_params=query_params,
214
+ headers=header_params,
215
+ post_params=post_params, body=body,
216
+ _preload_content=_preload_content,
217
+ _request_timeout=_request_timeout)
218
+ except ApiException as e:
219
+ if e.body:
220
+ e.body = e.body.decode('utf-8')
221
+ raise e
222
+
223
+ self.last_response = response_data
224
+
225
+ return_data = None # assuming deserialization is not needed
226
+ # data needs deserialization or returns HTTP data (deserialized) only
227
+ if _preload_content or _return_http_data_only:
228
+ response_type = response_types_map.get(str(response_data.status), None)
229
+ if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
230
+ # if not found, look for '1XX', '2XX', etc.
231
+ response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
232
+
233
+ if response_type == "bytearray":
234
+ response_data.data = response_data.data
235
+ else:
236
+ match = None
237
+ content_type = response_data.getheader('content-type')
238
+ if content_type is not None:
239
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
240
+ encoding = match.group(1) if match else "utf-8"
241
+ response_data.data = response_data.data.decode(encoding)
242
+
243
+ # deserialize response data
244
+ if response_type == "bytearray":
245
+ return_data = response_data.data
246
+ elif response_type:
247
+ return_data = self.deserialize(response_data, response_type)
248
+ else:
249
+ return_data = None
250
+
251
+ if _return_http_data_only:
252
+ return return_data
253
+ else:
254
+ return ApiResponse(status_code = response_data.status,
255
+ data = return_data,
256
+ headers = response_data.getheaders(),
257
+ raw_data = response_data.data)
258
+
259
+ def sanitize_for_serialization(self, obj):
260
+ """Builds a JSON POST object.
261
+
262
+ If obj is None, return None.
263
+ If obj is str, int, long, float, bool, return directly.
264
+ If obj is datetime.datetime, datetime.date
265
+ convert to string in iso8601 format.
266
+ If obj is list, sanitize each element in the list.
267
+ If obj is dict, return the dict.
268
+ If obj is OpenAPI model, return the properties dict.
269
+
270
+ :param obj: The data to serialize.
271
+ :return: The serialized form of data.
272
+ """
273
+ if obj is None:
274
+ return None
275
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
276
+ return obj
277
+ elif isinstance(obj, list):
278
+ return [self.sanitize_for_serialization(sub_obj)
279
+ for sub_obj in obj]
280
+ elif isinstance(obj, tuple):
281
+ return tuple(self.sanitize_for_serialization(sub_obj)
282
+ for sub_obj in obj)
283
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
284
+ return obj.isoformat()
285
+
286
+ if isinstance(obj, dict):
287
+ obj_dict = obj
288
+ else:
289
+ # Convert model obj to dict except
290
+ # attributes `openapi_types`, `attribute_map`
291
+ # and attributes which value is not None.
292
+ # Convert attribute name to json key in
293
+ # model definition for request.
294
+ obj_dict = obj.to_dict()
295
+
296
+ return {key: self.sanitize_for_serialization(val)
297
+ for key, val in obj_dict.items()}
298
+
299
+ def deserialize(self, response, response_type):
300
+ """Deserializes response into an object.
301
+
302
+ :param response: RESTResponse object to be deserialized.
303
+ :param response_type: class literal for
304
+ deserialized object, or string of class name.
305
+
306
+ :return: deserialized object.
307
+ """
308
+ # handle file downloading
309
+ # save response body into a tmp file and return the instance
310
+ if response_type == "file":
311
+ return self.__deserialize_file(response)
312
+
313
+ # fetch data from response object
314
+ try:
315
+ data = json.loads(response.data)
316
+ except ValueError:
317
+ data = response.data
318
+
319
+ return self.__deserialize(data, response_type)
320
+
321
+ def __deserialize(self, data, klass):
322
+ """Deserializes dict, list, str into an object.
323
+
324
+ :param data: dict, list or str.
325
+ :param klass: class literal, or string of class name.
326
+
327
+ :return: object.
328
+ """
329
+ if data is None:
330
+ return None
331
+
332
+ if isinstance(klass, str):
333
+ if klass.startswith('List['):
334
+ sub_kls = re.match(r'List\[(.*)]', klass).group(1)
335
+
336
+
337
+ try:
338
+ data = data['data']
339
+ except:
340
+ pass
341
+
342
+ return [self.__deserialize(sub_data, sub_kls)
343
+ for sub_data in data]
344
+
345
+ if klass.startswith('Dict['):
346
+ sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2)
347
+ return {k: self.__deserialize(v, sub_kls)
348
+ for k, v in data.items()}
349
+
350
+ # convert str to class
351
+ if klass in self.NATIVE_TYPES_MAPPING:
352
+ klass = self.NATIVE_TYPES_MAPPING[klass]
353
+ else:
354
+ klass = getattr(weheat.models, klass)
355
+
356
+ if klass in self.PRIMITIVE_TYPES:
357
+ return self.__deserialize_primitive(data, klass)
358
+ elif klass == object:
359
+ return self.__deserialize_object(data)
360
+ elif klass == datetime.date:
361
+ return self.__deserialize_date(data)
362
+ elif klass == datetime.datetime:
363
+ return self.__deserialize_datetime(data)
364
+ else:
365
+ return self.__deserialize_model(data, klass)
366
+
367
+ def call_api(self, resource_path, method,
368
+ path_params=None, query_params=None, header_params=None,
369
+ body=None, post_params=None, files=None,
370
+ response_types_map=None, auth_settings=None,
371
+ async_req=None, _return_http_data_only=None,
372
+ collection_formats=None, _preload_content=True,
373
+ _request_timeout=None, _host=None, _request_auth=None):
374
+ """Makes the HTTP request (synchronous) and returns deserialized data.
375
+
376
+ To make an async_req request, set the async_req parameter.
377
+
378
+ :param resource_path: Path to method endpoint.
379
+ :param method: Method to call.
380
+ :param path_params: Path parameters in the url.
381
+ :param query_params: Query parameters in the url.
382
+ :param header_params: Header parameters to be
383
+ placed in the request header.
384
+ :param body: Request body.
385
+ :param post_params dict: Request post form parameters,
386
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
387
+ :param auth_settings list: Auth Settings names for the request.
388
+ :param response: Response data type.
389
+ :param files dict: key -> filename, value -> filepath,
390
+ for `multipart/form-data`.
391
+ :param async_req bool: execute request asynchronously
392
+ :param _return_http_data_only: response data instead of ApiResponse
393
+ object with status code, headers, etc
394
+ :param _preload_content: if False, the ApiResponse.data will
395
+ be set to none and raw_data will store the
396
+ HTTP response body without reading/decoding.
397
+ Default is True.
398
+ :param collection_formats: dict of collection formats for path, query,
399
+ header, and post parameters.
400
+ :param _request_timeout: timeout setting for this request. If one
401
+ number provided, it will be total request
402
+ timeout. It can also be a pair (tuple) of
403
+ (connection, read) timeouts.
404
+ :param _request_auth: set to override the auth_settings for an a single
405
+ request; this effectively ignores the authentication
406
+ in the spec for a single request.
407
+ :type _request_token: dict, optional
408
+ :return:
409
+ If async_req parameter is True,
410
+ the request will be called asynchronously.
411
+ The method will return the request thread.
412
+ If parameter async_req is False or missing,
413
+ then the method will return the response directly.
414
+ """
415
+ args = (
416
+ resource_path,
417
+ method,
418
+ path_params,
419
+ query_params,
420
+ header_params,
421
+ body,
422
+ post_params,
423
+ files,
424
+ response_types_map,
425
+ auth_settings,
426
+ _return_http_data_only,
427
+ collection_formats,
428
+ _preload_content,
429
+ _request_timeout,
430
+ _host,
431
+ _request_auth,
432
+ )
433
+ if not async_req:
434
+ return self.__call_api(*args)
435
+
436
+ return self.pool.apply_async(self.__call_api, args)
437
+
438
+ def request(self, method, url, query_params=None, headers=None,
439
+ post_params=None, body=None, _preload_content=True,
440
+ _request_timeout=None):
441
+ """Makes the HTTP request using RESTClient."""
442
+ if method == "GET":
443
+ return self.rest_client.get_request(url,
444
+ query_params=query_params,
445
+ _preload_content=_preload_content,
446
+ _request_timeout=_request_timeout,
447
+ headers=headers)
448
+ elif method == "HEAD":
449
+ return self.rest_client.head_request(url,
450
+ query_params=query_params,
451
+ _preload_content=_preload_content,
452
+ _request_timeout=_request_timeout,
453
+ headers=headers)
454
+ elif method == "OPTIONS":
455
+ return self.rest_client.options_request(url,
456
+ query_params=query_params,
457
+ headers=headers,
458
+ _preload_content=_preload_content,
459
+ _request_timeout=_request_timeout)
460
+ elif method == "POST":
461
+ return self.rest_client.post_request(url,
462
+ query_params=query_params,
463
+ headers=headers,
464
+ post_params=post_params,
465
+ _preload_content=_preload_content,
466
+ _request_timeout=_request_timeout,
467
+ body=body)
468
+ elif method == "PUT":
469
+ return self.rest_client.put_request(url,
470
+ query_params=query_params,
471
+ headers=headers,
472
+ post_params=post_params,
473
+ _preload_content=_preload_content,
474
+ _request_timeout=_request_timeout,
475
+ body=body)
476
+ elif method == "PATCH":
477
+ return self.rest_client.patch_request(url,
478
+ query_params=query_params,
479
+ headers=headers,
480
+ post_params=post_params,
481
+ _preload_content=_preload_content,
482
+ _request_timeout=_request_timeout,
483
+ body=body)
484
+ elif method == "DELETE":
485
+ return self.rest_client.delete_request(url,
486
+ query_params=query_params,
487
+ headers=headers,
488
+ _preload_content=_preload_content,
489
+ _request_timeout=_request_timeout,
490
+ body=body)
491
+ else:
492
+ raise ApiValueError(
493
+ "http method must be `GET`, `HEAD`, `OPTIONS`,"
494
+ " `POST`, `PATCH`, `PUT` or `DELETE`."
495
+ )
496
+
497
+ def parameters_to_tuples(self, params, collection_formats):
498
+ """Get parameters as list of tuples, formatting collections.
499
+
500
+ :param params: Parameters as dict or list of two-tuples
501
+ :param dict collection_formats: Parameter collection formats
502
+ :return: Parameters as list of tuples, collections formatted
503
+ """
504
+ new_params = []
505
+ if collection_formats is None:
506
+ collection_formats = {}
507
+ for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
508
+ if k in collection_formats:
509
+ collection_format = collection_formats[k]
510
+ if collection_format == 'multi':
511
+ new_params.extend((k, value) for value in v)
512
+ else:
513
+ if collection_format == 'ssv':
514
+ delimiter = ' '
515
+ elif collection_format == 'tsv':
516
+ delimiter = '\t'
517
+ elif collection_format == 'pipes':
518
+ delimiter = '|'
519
+ else: # csv is the default
520
+ delimiter = ','
521
+ new_params.append(
522
+ (k, delimiter.join(str(value) for value in v)))
523
+ else:
524
+ new_params.append((k, v))
525
+ return new_params
526
+
527
+ def parameters_to_url_query(self, params, collection_formats):
528
+ """Get parameters as list of tuples, formatting collections.
529
+
530
+ :param params: Parameters as dict or list of two-tuples
531
+ :param dict collection_formats: Parameter collection formats
532
+ :return: URL query string (e.g. a=Hello%20World&b=123)
533
+ """
534
+ new_params = []
535
+ if collection_formats is None:
536
+ collection_formats = {}
537
+ for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
538
+ if isinstance(v, bool):
539
+ v = str(v).lower()
540
+ if isinstance(v, (int, float)):
541
+ v = str(v)
542
+ if isinstance(v, dict):
543
+ v = json.dumps(v)
544
+
545
+ if k in collection_formats:
546
+ collection_format = collection_formats[k]
547
+ if collection_format == 'multi':
548
+ new_params.extend((k, value) for value in v)
549
+ else:
550
+ if collection_format == 'ssv':
551
+ delimiter = ' '
552
+ elif collection_format == 'tsv':
553
+ delimiter = '\t'
554
+ elif collection_format == 'pipes':
555
+ delimiter = '|'
556
+ else: # csv is the default
557
+ delimiter = ','
558
+ new_params.append(
559
+ (k, delimiter.join(quote(str(value)) for value in v)))
560
+ else:
561
+ new_params.append((k, quote(str(v))))
562
+
563
+ return "&".join(["=".join(item) for item in new_params])
564
+
565
+ def files_parameters(self, files=None):
566
+ """Builds form parameters.
567
+
568
+ :param files: File parameters.
569
+ :return: Form parameters with files.
570
+ """
571
+ params = []
572
+
573
+ if files:
574
+ for k, v in files.items():
575
+ if not v:
576
+ continue
577
+ file_names = v if type(v) is list else [v]
578
+ for n in file_names:
579
+ with open(n, 'rb') as f:
580
+ filename = os.path.basename(f.name)
581
+ filedata = f.read()
582
+ mimetype = (mimetypes.guess_type(filename)[0] or
583
+ 'application/octet-stream')
584
+ params.append(
585
+ tuple([k, tuple([filename, filedata, mimetype])]))
586
+
587
+ return params
588
+
589
+ def select_header_accept(self, accepts):
590
+ """Returns `Accept` based on an array of accepts provided.
591
+
592
+ :param accepts: List of headers.
593
+ :return: Accept (e.g. application/json).
594
+ """
595
+ if not accepts:
596
+ return
597
+
598
+ for accept in accepts:
599
+ if re.search('json', accept, re.IGNORECASE):
600
+ return accept
601
+
602
+ return accepts[0]
603
+
604
+ def select_header_content_type(self, content_types):
605
+ """Returns `Content-Type` based on an array of content_types provided.
606
+
607
+ :param content_types: List of content-types.
608
+ :return: Content-Type (e.g. application/json).
609
+ """
610
+ if not content_types:
611
+ return None
612
+
613
+ for content_type in content_types:
614
+ if re.search('json', content_type, re.IGNORECASE):
615
+ return content_type
616
+
617
+ return content_types[0]
618
+
619
+ def update_params_for_auth(self, headers, queries, auth_settings,
620
+ resource_path, method, body,
621
+ request_auth=None):
622
+ """Updates header and query params based on authentication setting.
623
+
624
+ :param headers: Header parameters dict to be updated.
625
+ :param queries: Query parameters tuple list to be updated.
626
+ :param auth_settings: Authentication setting identifiers list.
627
+ :resource_path: A string representation of the HTTP request resource path.
628
+ :method: A string representation of the HTTP request method.
629
+ :body: A object representing the body of the HTTP request.
630
+ The object type is the return value of sanitize_for_serialization().
631
+ :param request_auth: if set, the provided settings will
632
+ override the token in the configuration.
633
+ """
634
+ if not auth_settings:
635
+ return
636
+
637
+ if request_auth:
638
+ self._apply_auth_params(headers, queries,
639
+ resource_path, method, body,
640
+ request_auth)
641
+ return
642
+
643
+ for auth in auth_settings:
644
+ auth_setting = self.configuration.auth_settings().get(auth)
645
+ if auth_setting:
646
+ self._apply_auth_params(headers, queries,
647
+ resource_path, method, body,
648
+ auth_setting)
649
+
650
+ def _apply_auth_params(self, headers, queries,
651
+ resource_path, method, body,
652
+ auth_setting):
653
+ """Updates the request parameters based on a single auth_setting
654
+
655
+ :param headers: Header parameters dict to be updated.
656
+ :param queries: Query parameters tuple list to be updated.
657
+ :resource_path: A string representation of the HTTP request resource path.
658
+ :method: A string representation of the HTTP request method.
659
+ :body: A object representing the body of the HTTP request.
660
+ The object type is the return value of sanitize_for_serialization().
661
+ :param auth_setting: auth settings for the endpoint
662
+ """
663
+ if auth_setting['in'] == 'cookie':
664
+ headers['Cookie'] = auth_setting['value']
665
+ elif auth_setting['in'] == 'header':
666
+ if auth_setting['type'] != 'http-signature':
667
+ headers[auth_setting['key']] = auth_setting['value']
668
+ elif auth_setting['in'] == 'query':
669
+ queries.append((auth_setting['key'], auth_setting['value']))
670
+ else:
671
+ raise ApiValueError(
672
+ 'Authentication token must be in `query` or `header`'
673
+ )
674
+
675
+ def __deserialize_file(self, response):
676
+ """Deserializes body to file
677
+
678
+ Saves response body into a file in a temporary folder,
679
+ using the filename from the `Content-Disposition` header if provided.
680
+
681
+ :param response: RESTResponse.
682
+ :return: file path.
683
+ """
684
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
685
+ os.close(fd)
686
+ os.remove(path)
687
+
688
+ content_disposition = response.getheader("Content-Disposition")
689
+ if content_disposition:
690
+ filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
691
+ content_disposition).group(1)
692
+ path = os.path.join(os.path.dirname(path), filename)
693
+
694
+ with open(path, "wb") as f:
695
+ f.write(response.data)
696
+
697
+ return path
698
+
699
+ def __deserialize_primitive(self, data, klass):
700
+ """Deserializes string to primitive type.
701
+
702
+ :param data: str.
703
+ :param klass: class literal.
704
+
705
+ :return: int, long, float, str, bool.
706
+ """
707
+ try:
708
+ return klass(data)
709
+ except UnicodeEncodeError:
710
+ return str(data)
711
+ except TypeError:
712
+ return data
713
+
714
+ def __deserialize_object(self, value):
715
+ """Return an original value.
716
+
717
+ :return: object.
718
+ """
719
+ return value
720
+
721
+ def __deserialize_date(self, string):
722
+ """Deserializes string to date.
723
+
724
+ :param string: str.
725
+ :return: date.
726
+ """
727
+ try:
728
+ return parse(string).date()
729
+ except ImportError:
730
+ return string
731
+ except ValueError:
732
+ raise rest.ApiException(
733
+ status=0,
734
+ reason="Failed to parse `{0}` as date object".format(string)
735
+ )
736
+
737
+ def __deserialize_datetime(self, string):
738
+ """Deserializes string to datetime.
739
+
740
+ The string should be in iso8601 datetime format.
741
+
742
+ :param string: str.
743
+ :return: datetime.
744
+ """
745
+ try:
746
+ return parse(string)
747
+ except ImportError:
748
+ return string
749
+ except ValueError:
750
+ raise rest.ApiException(
751
+ status=0,
752
+ reason=(
753
+ "Failed to parse `{0}` as datetime object"
754
+ .format(string)
755
+ )
756
+ )
757
+
758
+ def __deserialize_model(self, data, klass):
759
+ """Deserializes list or dict to model.
760
+
761
+ :param data: dict, list.
762
+ :param klass: class literal.
763
+ :return: model object.
764
+ """
765
+
766
+ return klass.from_dict(data)