lunchmoney-python-async 2.10.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 (92) hide show
  1. lunchmoney/__init__.py +205 -0
  2. lunchmoney/api/__init__.py +16 -0
  3. lunchmoney/api/categories_api.py +1499 -0
  4. lunchmoney/api/manual_accounts_api.py +1479 -0
  5. lunchmoney/api/me_api.py +293 -0
  6. lunchmoney/api/plaid_accounts_api.py +909 -0
  7. lunchmoney/api/recurring_items_api.py +702 -0
  8. lunchmoney/api/summary_api.py +434 -0
  9. lunchmoney/api/tags_api.py +1465 -0
  10. lunchmoney/api/transactions_api.py +914 -0
  11. lunchmoney/api/transactions_bulk_api.py +1527 -0
  12. lunchmoney/api/transactions_files_api.py +891 -0
  13. lunchmoney/api/transactions_group_api.py +601 -0
  14. lunchmoney/api/transactions_split_api.py +616 -0
  15. lunchmoney/api_client.py +808 -0
  16. lunchmoney/api_response.py +21 -0
  17. lunchmoney/configuration.py +616 -0
  18. lunchmoney/exceptions.py +217 -0
  19. lunchmoney/models/__init__.py +84 -0
  20. lunchmoney/models/account_type_enum.py +46 -0
  21. lunchmoney/models/aligned_category_totals_object.py +108 -0
  22. lunchmoney/models/aligned_summary_category_object.py +110 -0
  23. lunchmoney/models/aligned_summary_response_object.py +104 -0
  24. lunchmoney/models/category_object.py +146 -0
  25. lunchmoney/models/child_category_object.py +141 -0
  26. lunchmoney/models/child_transaction_object.py +219 -0
  27. lunchmoney/models/create_category_request_object.py +137 -0
  28. lunchmoney/models/create_category_request_object_children_inner.py +159 -0
  29. lunchmoney/models/create_manual_account_request_object.py +138 -0
  30. lunchmoney/models/create_manual_account_request_object_balance.py +145 -0
  31. lunchmoney/models/create_new_transactions_request.py +103 -0
  32. lunchmoney/models/create_tag_request_object.py +112 -0
  33. lunchmoney/models/currency_enum.py +198 -0
  34. lunchmoney/models/delete_category_response_with_dependencies.py +94 -0
  35. lunchmoney/models/delete_category_response_with_dependencies_dependents.py +98 -0
  36. lunchmoney/models/delete_tag_response_with_dependencies.py +94 -0
  37. lunchmoney/models/delete_tag_response_with_dependencies_dependents.py +90 -0
  38. lunchmoney/models/delete_transactions_request.py +89 -0
  39. lunchmoney/models/error_response_object.py +98 -0
  40. lunchmoney/models/error_response_object_errors_inner.py +101 -0
  41. lunchmoney/models/get_all_categories200_response.py +96 -0
  42. lunchmoney/models/get_all_manual_accounts200_response.py +96 -0
  43. lunchmoney/models/get_all_plaid_accounts200_response.py +96 -0
  44. lunchmoney/models/get_all_recurring200_response.py +96 -0
  45. lunchmoney/models/get_all_tags200_response.py +96 -0
  46. lunchmoney/models/get_all_transactions200_response.py +100 -0
  47. lunchmoney/models/get_all_transactions_created_since_parameter.py +145 -0
  48. lunchmoney/models/get_budget_summary200_response.py +138 -0
  49. lunchmoney/models/get_transaction_attachment_url200_response.py +91 -0
  50. lunchmoney/models/group_transactions_request.py +122 -0
  51. lunchmoney/models/insert_transaction_object.py +164 -0
  52. lunchmoney/models/insert_transaction_object_amount.py +145 -0
  53. lunchmoney/models/insert_transactions_response_object.py +106 -0
  54. lunchmoney/models/manual_account_object.py +158 -0
  55. lunchmoney/models/non_aligned_category_totals_object.py +94 -0
  56. lunchmoney/models/non_aligned_summary_category_object.py +94 -0
  57. lunchmoney/models/non_aligned_summary_response_object.py +104 -0
  58. lunchmoney/models/plaid_account_object.py +168 -0
  59. lunchmoney/models/recurring_object.py +143 -0
  60. lunchmoney/models/recurring_object_matches.py +105 -0
  61. lunchmoney/models/recurring_object_matches_found_transactions_inner.py +91 -0
  62. lunchmoney/models/recurring_object_overrides.py +92 -0
  63. lunchmoney/models/recurring_object_transaction_criteria.py +149 -0
  64. lunchmoney/models/skipped_existing_external_id_object.py +108 -0
  65. lunchmoney/models/split_transaction_object.py +102 -0
  66. lunchmoney/models/split_transaction_object_amount.py +145 -0
  67. lunchmoney/models/split_transaction_request.py +97 -0
  68. lunchmoney/models/summary_category_occurrence_object.py +126 -0
  69. lunchmoney/models/summary_recurring_transaction_object.py +100 -0
  70. lunchmoney/models/summary_rollover_pool_adjustment_object.py +98 -0
  71. lunchmoney/models/summary_rollover_pool_object.py +98 -0
  72. lunchmoney/models/summary_totals_breakdown_object.py +98 -0
  73. lunchmoney/models/summary_totals_object.py +97 -0
  74. lunchmoney/models/tag_object.py +125 -0
  75. lunchmoney/models/transaction_attachment_object.py +106 -0
  76. lunchmoney/models/transaction_object.py +229 -0
  77. lunchmoney/models/update_category_request_object.py +156 -0
  78. lunchmoney/models/update_manual_account_request_object.py +156 -0
  79. lunchmoney/models/update_manual_account_request_object_balance.py +145 -0
  80. lunchmoney/models/update_tag_request_object.py +126 -0
  81. lunchmoney/models/update_transaction_object.py +228 -0
  82. lunchmoney/models/update_transaction_object_amount.py +145 -0
  83. lunchmoney/models/update_transactions200_response.py +96 -0
  84. lunchmoney/models/update_transactions_request.py +97 -0
  85. lunchmoney/models/update_transactions_request_transactions_inner.py +228 -0
  86. lunchmoney/models/user_object.py +106 -0
  87. lunchmoney/py.typed +0 -0
  88. lunchmoney/rest.py +195 -0
  89. lunchmoney_python_async-2.10.0.dist-info/METADATA +287 -0
  90. lunchmoney_python_async-2.10.0.dist-info/RECORD +92 -0
  91. lunchmoney_python_async-2.10.0.dist-info/WHEEL +5 -0
  92. lunchmoney_python_async-2.10.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,808 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Lunch Money API - v2
5
+
6
+ Welcome to the Lunch Money v2 API. A working version of this API is now available through these docs, or directly at: `https://api.lunchmoney.dev/v2` <span class=\"red-text\"><strong>This is in alpha launch of a major API update. It is still subject to change during this alpha review period and bugs may still exist. Users are strongly encouraged to use the mock service or to create a test budget with example data as the first step to interacting with the v2 API.</strong></span> See the [Getting Started Guide](https://alpha.lunchmoney.dev/v2/getting-started) for more information on using a test budget.<br<br> If you are new to the v2 API, you may wish to review the [v2 API Overview of Changes](https://alpha.lunchmoney.dev/v2/changelog). ### Static Mock Server You may also use these docs to explore the API using a static mock server endpoint.<p> This enables users to become familiar with the API without having to create an access token, and eliminates the possibility of modifying real data. <p> To access this endpoint select the second endpoint in the the \"Server\" dropdown to the right. When selected you should see \"Static Mock v2 Lunch Money API Server\".<br> When using this server, set your Bearer token to any string with 11 or more characters. ### Migrating from V1 The v2 API is NOT backwards compatible with the v1 API. Developers are encouraged to review the [Migration Guide](https://alpha.lunchmoney.dev/v2/migration-guide) to understand the changes and plan their migration. ### Acknowledgments If you have been providing feedback on the API during our iterative design process, **THANK YOU**. We are happy to provide the opportunity to finally interact with the working API that was built based on your feedback. ### Useful links: - [Getting Started](https://alpha.lunchmoney.dev/v2/getting-started) - [v2 API Changelog](https://alpha.lunchmoney.dev/v2/changelog) - [Migration Guide](https://alpha.lunchmoney.dev/v2/migration-guide) - [Rate Limits](https://alpha.lunchmoney.dev/v2/rate-limits) - [Current v1 Lunch Money API Documentation](https://lunchmoney.dev) - [Awesome Lunch Money Projects](https://github.com/lunch-money/awesome-lunchmoney?tab=readme-ov-file)
7
+
8
+ The version of the OpenAPI document: 2.8.4
9
+ Contact: devsupport@lunchmoney.app
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
+ import uuid
26
+
27
+ from urllib.parse import quote
28
+ from typing import Tuple, Optional, List, Dict, Union
29
+ from pydantic import SecretStr
30
+
31
+ from lunchmoney.configuration import Configuration
32
+ from lunchmoney.api_response import ApiResponse, T as ApiResponseT
33
+ import lunchmoney.models
34
+ from lunchmoney import rest
35
+ from lunchmoney.exceptions import (
36
+ ApiValueError,
37
+ ApiException,
38
+ BadRequestException,
39
+ UnauthorizedException,
40
+ ForbiddenException,
41
+ NotFoundException,
42
+ ServiceException
43
+ )
44
+
45
+ RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]]
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__(
78
+ self,
79
+ configuration=None,
80
+ header_name=None,
81
+ header_value=None,
82
+ cookie=None
83
+ ) -> None:
84
+ # use default configuration if none is provided
85
+ if configuration is None:
86
+ configuration = Configuration.get_default()
87
+ self.configuration = configuration
88
+
89
+ self.rest_client = rest.RESTClientObject(configuration)
90
+ self.default_headers = {}
91
+ if header_name is not None:
92
+ self.default_headers[header_name] = header_value
93
+ self.cookie = cookie
94
+ # Set default User-Agent.
95
+ self.user_agent = 'OpenAPI-Generator/2.10.0/python'
96
+ self.client_side_validation = configuration.client_side_validation
97
+
98
+ async def __aenter__(self):
99
+ return self
100
+
101
+ async def __aexit__(self, exc_type, exc_value, traceback):
102
+ await self.close()
103
+
104
+ async def close(self):
105
+ await self.rest_client.close()
106
+
107
+ @property
108
+ def user_agent(self):
109
+ """User agent for this API client"""
110
+ return self.default_headers['User-Agent']
111
+
112
+ @user_agent.setter
113
+ def user_agent(self, value):
114
+ self.default_headers['User-Agent'] = value
115
+
116
+ def set_default_header(self, header_name, header_value):
117
+ self.default_headers[header_name] = header_value
118
+
119
+
120
+ _default = None
121
+
122
+ @classmethod
123
+ def get_default(cls):
124
+ """Return new instance of ApiClient.
125
+
126
+ This method returns newly created, based on default constructor,
127
+ object of ApiClient class or returns a copy of default
128
+ ApiClient.
129
+
130
+ :return: The ApiClient object.
131
+ """
132
+ if cls._default is None:
133
+ cls._default = ApiClient()
134
+ return cls._default
135
+
136
+ @classmethod
137
+ def set_default(cls, default):
138
+ """Set default instance of ApiClient.
139
+
140
+ It stores default ApiClient.
141
+
142
+ :param default: object of ApiClient.
143
+ """
144
+ cls._default = default
145
+
146
+ def param_serialize(
147
+ self,
148
+ method,
149
+ resource_path,
150
+ path_params=None,
151
+ query_params=None,
152
+ header_params=None,
153
+ body=None,
154
+ post_params=None,
155
+ files=None, auth_settings=None,
156
+ collection_formats=None,
157
+ _host=None,
158
+ _request_auth=None
159
+ ) -> RequestSerialized:
160
+
161
+ """Builds the HTTP request params needed by the request.
162
+ :param method: Method to call.
163
+ :param resource_path: Path to method endpoint.
164
+ :param path_params: Path parameters in the url.
165
+ :param query_params: Query parameters in the url.
166
+ :param header_params: Header parameters to be
167
+ placed in the request header.
168
+ :param body: Request body.
169
+ :param post_params dict: Request post form parameters,
170
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
171
+ :param auth_settings list: Auth Settings names for the request.
172
+ :param files dict: key -> filename, value -> filepath,
173
+ for `multipart/form-data`.
174
+ :param collection_formats: dict of collection formats for path, query,
175
+ header, and post parameters.
176
+ :param _request_auth: set to override the auth_settings for an a single
177
+ request; this effectively ignores the authentication
178
+ in the spec for a single request.
179
+ :return: tuple of form (path, http_method, query_params, header_params,
180
+ body, post_params, files)
181
+ """
182
+
183
+ config = self.configuration
184
+
185
+ # header parameters
186
+ header_params = header_params or {}
187
+ header_params.update(self.default_headers)
188
+ if self.cookie:
189
+ header_params['Cookie'] = self.cookie
190
+ if header_params:
191
+ header_params = self.sanitize_for_serialization(header_params)
192
+ header_params = dict(
193
+ self.parameters_to_tuples(header_params,collection_formats)
194
+ )
195
+
196
+ # path parameters
197
+ if path_params:
198
+ path_params = self.sanitize_for_serialization(path_params)
199
+ path_params = self.parameters_to_tuples(
200
+ path_params,
201
+ collection_formats
202
+ )
203
+ for k, v in path_params:
204
+ # specified safe chars, encode everything
205
+ resource_path = resource_path.replace(
206
+ '{%s}' % k,
207
+ quote(str(v), safe=config.safe_chars_for_path_param)
208
+ )
209
+
210
+ # post parameters
211
+ if post_params or files:
212
+ post_params = post_params if post_params else []
213
+ post_params = self.sanitize_for_serialization(post_params)
214
+ post_params = self.parameters_to_tuples(
215
+ post_params,
216
+ collection_formats
217
+ )
218
+ if files:
219
+ post_params.extend(self.files_parameters(files))
220
+
221
+ # auth setting
222
+ self.update_params_for_auth(
223
+ header_params,
224
+ query_params,
225
+ auth_settings,
226
+ resource_path,
227
+ method,
228
+ body,
229
+ request_auth=_request_auth
230
+ )
231
+
232
+ # body
233
+ if body:
234
+ body = self.sanitize_for_serialization(body)
235
+
236
+ # request url
237
+ if _host is None or self.configuration.ignore_operation_servers:
238
+ url = self.configuration.host + resource_path
239
+ else:
240
+ # use server/host defined in path or operation instead
241
+ url = _host + resource_path
242
+
243
+ # query parameters
244
+ if query_params:
245
+ query_params = self.sanitize_for_serialization(query_params)
246
+ url_query = self.parameters_to_url_query(
247
+ query_params,
248
+ collection_formats
249
+ )
250
+ url += "?" + url_query
251
+
252
+ return method, url, header_params, body, post_params
253
+
254
+
255
+ async def call_api(
256
+ self,
257
+ method,
258
+ url,
259
+ header_params=None,
260
+ body=None,
261
+ post_params=None,
262
+ _request_timeout=None
263
+ ) -> rest.RESTResponse:
264
+ """Makes the HTTP request (synchronous)
265
+ :param method: Method to call.
266
+ :param url: Path to method endpoint.
267
+ :param header_params: Header parameters to be
268
+ placed in the request header.
269
+ :param body: Request body.
270
+ :param post_params dict: Request post form parameters,
271
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
272
+ :param _request_timeout: timeout setting for this request.
273
+ :return: RESTResponse
274
+ """
275
+
276
+ try:
277
+ # perform request and return response
278
+ response_data = await self.rest_client.request(
279
+ method, url,
280
+ headers=header_params,
281
+ body=body, post_params=post_params,
282
+ _request_timeout=_request_timeout
283
+ )
284
+
285
+ except ApiException as e:
286
+ raise e
287
+
288
+ return response_data
289
+
290
+ def response_deserialize(
291
+ self,
292
+ response_data: rest.RESTResponse,
293
+ response_types_map: Optional[Dict[str, ApiResponseT]]=None
294
+ ) -> ApiResponse[ApiResponseT]:
295
+ """Deserializes response into an object.
296
+ :param response_data: RESTResponse object to be deserialized.
297
+ :param response_types_map: dict of response types.
298
+ :return: ApiResponse
299
+ """
300
+
301
+ msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
302
+ assert response_data.data is not None, msg
303
+
304
+ response_type = response_types_map.get(str(response_data.status), None)
305
+ if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
306
+ # if not found, look for '1XX', '2XX', etc.
307
+ response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
308
+
309
+ # deserialize response data
310
+ response_text = None
311
+ return_data = None
312
+ try:
313
+ if response_type == "bytearray":
314
+ return_data = response_data.data
315
+ elif response_type == "file":
316
+ return_data = self.__deserialize_file(response_data)
317
+ elif response_type is not None:
318
+ match = None
319
+ content_type = response_data.getheader('content-type')
320
+ if content_type is not None:
321
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
322
+ encoding = match.group(1) if match else "utf-8"
323
+ response_text = response_data.data.decode(encoding)
324
+ return_data = self.deserialize(response_text, response_type, content_type)
325
+ finally:
326
+ if not 200 <= response_data.status <= 299:
327
+ raise ApiException.from_response(
328
+ http_resp=response_data,
329
+ body=response_text,
330
+ data=return_data,
331
+ )
332
+
333
+ return ApiResponse(
334
+ status_code = response_data.status,
335
+ data = return_data,
336
+ headers = response_data.getheaders(),
337
+ raw_data = response_data.data
338
+ )
339
+
340
+ def sanitize_for_serialization(self, obj):
341
+ """Builds a JSON POST object.
342
+
343
+ If obj is None, return None.
344
+ If obj is SecretStr, return obj.get_secret_value()
345
+ If obj is str, int, long, float, bool, return directly.
346
+ If obj is datetime.datetime, datetime.date
347
+ convert to string in iso8601 format.
348
+ If obj is decimal.Decimal return string representation.
349
+ If obj is list, sanitize each element in the list.
350
+ If obj is dict, return the dict.
351
+ If obj is OpenAPI model, return the properties dict.
352
+
353
+ :param obj: The data to serialize.
354
+ :return: The serialized form of data.
355
+ """
356
+ if obj is None:
357
+ return None
358
+ elif isinstance(obj, Enum):
359
+ return obj.value
360
+ elif isinstance(obj, SecretStr):
361
+ return obj.get_secret_value()
362
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
363
+ return obj
364
+ elif isinstance(obj, uuid.UUID):
365
+ return str(obj)
366
+ elif isinstance(obj, list):
367
+ return [
368
+ self.sanitize_for_serialization(sub_obj) for sub_obj in obj
369
+ ]
370
+ elif isinstance(obj, tuple):
371
+ return tuple(
372
+ self.sanitize_for_serialization(sub_obj) for sub_obj in obj
373
+ )
374
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
375
+ return obj.isoformat()
376
+ elif isinstance(obj, decimal.Decimal):
377
+ return str(obj)
378
+
379
+ elif isinstance(obj, dict):
380
+ obj_dict = obj
381
+ else:
382
+ # Convert model obj to dict except
383
+ # attributes `openapi_types`, `attribute_map`
384
+ # and attributes which value is not None.
385
+ # Convert attribute name to json key in
386
+ # model definition for request.
387
+ if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')):
388
+ obj_dict = obj.to_dict()
389
+ else:
390
+ obj_dict = obj.__dict__
391
+
392
+ if isinstance(obj_dict, list):
393
+ # here we handle instances that can either be a list or something else, and only became a real list by calling to_dict()
394
+ return self.sanitize_for_serialization(obj_dict)
395
+
396
+ return {
397
+ key: self.sanitize_for_serialization(val)
398
+ for key, val in obj_dict.items()
399
+ }
400
+
401
+ def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]):
402
+ """Deserializes response into an object.
403
+
404
+ :param response: RESTResponse object to be deserialized.
405
+ :param response_type: class literal for
406
+ deserialized object, or string of class name.
407
+ :param content_type: content type of response.
408
+
409
+ :return: deserialized object.
410
+ """
411
+
412
+ # fetch data from response object
413
+ if content_type is None:
414
+ try:
415
+ data = json.loads(response_text)
416
+ except ValueError:
417
+ data = response_text
418
+ elif re.match(r'^application/(json|[\w!#$&.+\-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE):
419
+ if response_text == "":
420
+ data = ""
421
+ else:
422
+ data = json.loads(response_text)
423
+ elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE):
424
+ data = response_text
425
+ else:
426
+ raise ApiException(
427
+ status=0,
428
+ reason="Unsupported content type: {0}".format(content_type)
429
+ )
430
+
431
+ return self.__deserialize(data, response_type)
432
+
433
+ def __deserialize(self, data, klass):
434
+ """Deserializes dict, list, str into an object.
435
+
436
+ :param data: dict, list or str.
437
+ :param klass: class literal, or string of class name.
438
+
439
+ :return: object.
440
+ """
441
+ if data is None:
442
+ return None
443
+
444
+ if isinstance(klass, str):
445
+ if klass.startswith('List['):
446
+ m = re.match(r'List\[(.*)]', klass)
447
+ assert m is not None, "Malformed List type definition"
448
+ sub_kls = m.group(1)
449
+ return [self.__deserialize(sub_data, sub_kls)
450
+ for sub_data in data]
451
+
452
+ if klass.startswith('Dict['):
453
+ m = re.match(r'Dict\[([^,]*), (.*)]', klass)
454
+ assert m is not None, "Malformed Dict type definition"
455
+ sub_kls = m.group(2)
456
+ return {k: self.__deserialize(v, sub_kls)
457
+ for k, v in data.items()}
458
+
459
+ # convert str to class
460
+ if klass in self.NATIVE_TYPES_MAPPING:
461
+ klass = self.NATIVE_TYPES_MAPPING[klass]
462
+ else:
463
+ klass = getattr(lunchmoney.models, klass)
464
+
465
+ if klass in self.PRIMITIVE_TYPES:
466
+ return self.__deserialize_primitive(data, klass)
467
+ elif klass is object:
468
+ return self.__deserialize_object(data)
469
+ elif klass is datetime.date:
470
+ return self.__deserialize_date(data)
471
+ elif klass is datetime.datetime:
472
+ return self.__deserialize_datetime(data)
473
+ elif klass is decimal.Decimal:
474
+ return decimal.Decimal(data)
475
+ elif issubclass(klass, Enum):
476
+ return self.__deserialize_enum(data, klass)
477
+ else:
478
+ return self.__deserialize_model(data, klass)
479
+
480
+ def parameters_to_tuples(self, params, collection_formats):
481
+ """Get parameters as list of tuples, formatting collections.
482
+
483
+ :param params: Parameters as dict or list of two-tuples
484
+ :param dict collection_formats: Parameter collection formats
485
+ :return: Parameters as list of tuples, collections formatted
486
+ """
487
+ new_params: List[Tuple[str, str]] = []
488
+ if collection_formats is None:
489
+ collection_formats = {}
490
+ for k, v in params.items() if isinstance(params, dict) else params:
491
+ if k in collection_formats:
492
+ collection_format = collection_formats[k]
493
+ if collection_format == 'multi':
494
+ new_params.extend((k, value) for value in v)
495
+ else:
496
+ if collection_format == 'ssv':
497
+ delimiter = ' '
498
+ elif collection_format == 'tsv':
499
+ delimiter = '\t'
500
+ elif collection_format == 'pipes':
501
+ delimiter = '|'
502
+ else: # csv is the default
503
+ delimiter = ','
504
+ new_params.append(
505
+ (k, delimiter.join(str(value) for value in v)))
506
+ else:
507
+ new_params.append((k, v))
508
+ return new_params
509
+
510
+ def parameters_to_url_query(self, params, collection_formats):
511
+ """Get parameters as list of tuples, formatting collections.
512
+
513
+ :param params: Parameters as dict or list of two-tuples
514
+ :param dict collection_formats: Parameter collection formats
515
+ :return: URL query string (e.g. a=Hello%20World&b=123)
516
+ """
517
+ new_params: List[Tuple[str, str]] = []
518
+ if collection_formats is None:
519
+ collection_formats = {}
520
+ for k, v in params.items() if isinstance(params, dict) else params:
521
+ if isinstance(v, bool):
522
+ v = str(v).lower()
523
+ if isinstance(v, (int, float)):
524
+ v = str(v)
525
+ if isinstance(v, dict):
526
+ v = json.dumps(v)
527
+
528
+ if k in collection_formats:
529
+ collection_format = collection_formats[k]
530
+ if collection_format == 'multi':
531
+ new_params.extend((k, quote(str(value))) for value in v)
532
+ else:
533
+ if collection_format == 'ssv':
534
+ delimiter = ' '
535
+ elif collection_format == 'tsv':
536
+ delimiter = '\t'
537
+ elif collection_format == 'pipes':
538
+ delimiter = '|'
539
+ else: # csv is the default
540
+ delimiter = ','
541
+ new_params.append(
542
+ (k, delimiter.join(quote(str(value)) for value in v))
543
+ )
544
+ else:
545
+ new_params.append((k, quote(str(v))))
546
+
547
+ return "&".join(["=".join(map(str, item)) for item in new_params])
548
+
549
+ def files_parameters(
550
+ self,
551
+ files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]],
552
+ ):
553
+ """Builds form parameters.
554
+
555
+ :param files: File parameters.
556
+ :return: Form parameters with files.
557
+ """
558
+ params = []
559
+ for k, v in files.items():
560
+ if isinstance(v, str):
561
+ with open(v, 'rb') as f:
562
+ filename = os.path.basename(f.name)
563
+ filedata = f.read()
564
+ elif isinstance(v, bytes):
565
+ filename = k
566
+ filedata = v
567
+ elif isinstance(v, tuple):
568
+ filename, filedata = v
569
+ elif isinstance(v, list):
570
+ for file_param in v:
571
+ params.extend(self.files_parameters({k: file_param}))
572
+ continue
573
+ else:
574
+ raise ValueError("Unsupported file value")
575
+ mimetype = (
576
+ mimetypes.guess_type(filename)[0]
577
+ or 'application/octet-stream'
578
+ )
579
+ params.append(
580
+ tuple([k, tuple([filename, filedata, mimetype])])
581
+ )
582
+ return params
583
+
584
+ def select_header_accept(self, accepts: List[str]) -> Optional[str]:
585
+ """Returns `Accept` based on an array of accepts provided.
586
+
587
+ :param accepts: List of headers.
588
+ :return: Accept (e.g. application/json).
589
+ """
590
+ if not accepts:
591
+ return None
592
+
593
+ for accept in accepts:
594
+ if re.search('json', accept, re.IGNORECASE):
595
+ return accept
596
+
597
+ return accepts[0]
598
+
599
+ def select_header_content_type(self, content_types):
600
+ """Returns `Content-Type` based on an array of content_types provided.
601
+
602
+ :param content_types: List of content-types.
603
+ :return: Content-Type (e.g. application/json).
604
+ """
605
+ if not content_types:
606
+ return None
607
+
608
+ for content_type in content_types:
609
+ if re.search('json', content_type, re.IGNORECASE):
610
+ return content_type
611
+
612
+ return content_types[0]
613
+
614
+ def update_params_for_auth(
615
+ self,
616
+ headers,
617
+ queries,
618
+ auth_settings,
619
+ resource_path,
620
+ method,
621
+ body,
622
+ request_auth=None
623
+ ) -> None:
624
+ """Updates header and query params based on authentication setting.
625
+
626
+ :param headers: Header parameters dict to be updated.
627
+ :param queries: Query parameters tuple list to be updated.
628
+ :param auth_settings: Authentication setting identifiers list.
629
+ :resource_path: A string representation of the HTTP request resource path.
630
+ :method: A string representation of the HTTP request method.
631
+ :body: A object representing the body of the HTTP request.
632
+ The object type is the return value of sanitize_for_serialization().
633
+ :param request_auth: if set, the provided settings will
634
+ override the token in the configuration.
635
+ """
636
+ if not auth_settings:
637
+ return
638
+
639
+ if request_auth:
640
+ self._apply_auth_params(
641
+ headers,
642
+ queries,
643
+ resource_path,
644
+ method,
645
+ body,
646
+ request_auth
647
+ )
648
+ else:
649
+ for auth in auth_settings:
650
+ auth_setting = self.configuration.auth_settings().get(auth)
651
+ if auth_setting:
652
+ self._apply_auth_params(
653
+ headers,
654
+ queries,
655
+ resource_path,
656
+ method,
657
+ body,
658
+ auth_setting
659
+ )
660
+
661
+ def _apply_auth_params(
662
+ self,
663
+ headers,
664
+ queries,
665
+ resource_path,
666
+ method,
667
+ body,
668
+ auth_setting
669
+ ) -> None:
670
+ """Updates the request parameters based on a single auth_setting
671
+
672
+ :param headers: Header parameters dict to be updated.
673
+ :param queries: Query parameters tuple list to be updated.
674
+ :resource_path: A string representation of the HTTP request resource path.
675
+ :method: A string representation of the HTTP request method.
676
+ :body: A object representing the body of the HTTP request.
677
+ The object type is the return value of sanitize_for_serialization().
678
+ :param auth_setting: auth settings for the endpoint
679
+ """
680
+ if auth_setting['in'] == 'cookie':
681
+ headers['Cookie'] = auth_setting['value']
682
+ elif auth_setting['in'] == 'header':
683
+ if auth_setting['type'] != 'http-signature':
684
+ headers[auth_setting['key']] = auth_setting['value']
685
+ elif auth_setting['in'] == 'query':
686
+ queries.append((auth_setting['key'], auth_setting['value']))
687
+ else:
688
+ raise ApiValueError(
689
+ 'Authentication token must be in `query` or `header`'
690
+ )
691
+
692
+ def __deserialize_file(self, response):
693
+ """Deserializes body to file
694
+
695
+ Saves response body into a file in a temporary folder,
696
+ using the filename from the `Content-Disposition` header if provided.
697
+
698
+ handle file downloading
699
+ save response body into a tmp file and return the instance
700
+
701
+ :param response: RESTResponse.
702
+ :return: file path.
703
+ """
704
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
705
+ os.close(fd)
706
+ os.remove(path)
707
+
708
+ content_disposition = response.getheader("Content-Disposition")
709
+ if content_disposition:
710
+ m = re.search(
711
+ r'filename=[\'"]?([^\'"\s]+)[\'"]?',
712
+ content_disposition
713
+ )
714
+ assert m is not None, "Unexpected 'content-disposition' header value"
715
+ filename = m.group(1)
716
+ path = os.path.join(os.path.dirname(path), filename)
717
+
718
+ with open(path, "wb") as f:
719
+ f.write(response.data)
720
+
721
+ return path
722
+
723
+ def __deserialize_primitive(self, data, klass):
724
+ """Deserializes string to primitive type.
725
+
726
+ :param data: str.
727
+ :param klass: class literal.
728
+
729
+ :return: int, long, float, str, bool.
730
+ """
731
+ try:
732
+ return klass(data)
733
+ except UnicodeEncodeError:
734
+ return str(data)
735
+ except TypeError:
736
+ return data
737
+
738
+ def __deserialize_object(self, value):
739
+ """Return an original value.
740
+
741
+ :return: object.
742
+ """
743
+ return value
744
+
745
+ def __deserialize_date(self, string):
746
+ """Deserializes string to date.
747
+
748
+ :param string: str.
749
+ :return: date.
750
+ """
751
+ try:
752
+ return parse(string).date()
753
+ except ImportError:
754
+ return string
755
+ except ValueError:
756
+ raise rest.ApiException(
757
+ status=0,
758
+ reason="Failed to parse `{0}` as date object".format(string)
759
+ )
760
+
761
+ def __deserialize_datetime(self, string):
762
+ """Deserializes string to datetime.
763
+
764
+ The string should be in iso8601 datetime format.
765
+
766
+ :param string: str.
767
+ :return: datetime.
768
+ """
769
+ try:
770
+ return parse(string)
771
+ except ImportError:
772
+ return string
773
+ except ValueError:
774
+ raise rest.ApiException(
775
+ status=0,
776
+ reason=(
777
+ "Failed to parse `{0}` as datetime object"
778
+ .format(string)
779
+ )
780
+ )
781
+
782
+ def __deserialize_enum(self, data, klass):
783
+ """Deserializes primitive type to enum.
784
+
785
+ :param data: primitive type.
786
+ :param klass: class literal.
787
+ :return: enum value.
788
+ """
789
+ try:
790
+ return klass(data)
791
+ except ValueError:
792
+ raise rest.ApiException(
793
+ status=0,
794
+ reason=(
795
+ "Failed to parse `{0}` as `{1}`"
796
+ .format(data, klass)
797
+ )
798
+ )
799
+
800
+ def __deserialize_model(self, data, klass):
801
+ """Deserializes list or dict to model.
802
+
803
+ :param data: dict, list.
804
+ :param klass: class literal.
805
+ :return: model object.
806
+ """
807
+
808
+ return klass.from_dict(data)