aind-metadata-service-async-client 1.0.7__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 aind-metadata-service-async-client might be problematic. Click here for more details.

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