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

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