signwell-sdk-python 0.1.0__py3-none-any.whl

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