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