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