daytona_api_client_async 0.21.3a0__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 daytona_api_client_async might be problematic. Click here for more details.

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