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