lunchmoney-python 2.9.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 +805 -0
  16. lunchmoney/api_response.py +21 -0
  17. lunchmoney/configuration.py +620 -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 +259 -0
  89. lunchmoney_python-2.9.0.dist-info/METADATA +285 -0
  90. lunchmoney_python-2.9.0.dist-info/RECORD +92 -0
  91. lunchmoney_python-2.9.0.dist-info/WHEEL +5 -0
  92. lunchmoney_python-2.9.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ """API response object."""
2
+
3
+ from __future__ import annotations
4
+ from typing import Optional, Generic, Mapping, TypeVar
5
+ from pydantic import Field, StrictInt, StrictBytes, BaseModel
6
+
7
+ T = TypeVar("T")
8
+
9
+ class ApiResponse(BaseModel, Generic[T]):
10
+ """
11
+ API response object
12
+ """
13
+
14
+ status_code: StrictInt = Field(description="HTTP status code")
15
+ headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers")
16
+ data: T = Field(description="Deserialized data given the data type")
17
+ raw_data: StrictBytes = Field(description="Raw data (HTTP response body)")
18
+
19
+ model_config = {
20
+ "arbitrary_types_allowed": True
21
+ }
@@ -0,0 +1,620 @@
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 copy
17
+ import http.client as httplib
18
+ import logging
19
+ from logging import FileHandler
20
+ import multiprocessing
21
+ import sys
22
+ from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict, Union
23
+ from typing_extensions import NotRequired, Self
24
+
25
+ import urllib3
26
+
27
+
28
+ JSON_SCHEMA_VALIDATION_KEYWORDS = {
29
+ 'multipleOf', 'maximum', 'exclusiveMaximum',
30
+ 'minimum', 'exclusiveMinimum', 'maxLength',
31
+ 'minLength', 'pattern', 'maxItems', 'minItems'
32
+ }
33
+
34
+ ServerVariablesT = Dict[str, str]
35
+
36
+ GenericAuthSetting = TypedDict(
37
+ "GenericAuthSetting",
38
+ {
39
+ "type": str,
40
+ "in": str,
41
+ "key": str,
42
+ "value": str,
43
+ },
44
+ )
45
+
46
+
47
+ OAuth2AuthSetting = TypedDict(
48
+ "OAuth2AuthSetting",
49
+ {
50
+ "type": Literal["oauth2"],
51
+ "in": Literal["header"],
52
+ "key": Literal["Authorization"],
53
+ "value": str,
54
+ },
55
+ )
56
+
57
+
58
+ APIKeyAuthSetting = TypedDict(
59
+ "APIKeyAuthSetting",
60
+ {
61
+ "type": Literal["api_key"],
62
+ "in": str,
63
+ "key": str,
64
+ "value": Optional[str],
65
+ },
66
+ )
67
+
68
+
69
+ BasicAuthSetting = TypedDict(
70
+ "BasicAuthSetting",
71
+ {
72
+ "type": Literal["basic"],
73
+ "in": Literal["header"],
74
+ "key": Literal["Authorization"],
75
+ "value": Optional[str],
76
+ },
77
+ )
78
+
79
+
80
+ BearerFormatAuthSetting = TypedDict(
81
+ "BearerFormatAuthSetting",
82
+ {
83
+ "type": Literal["bearer"],
84
+ "in": Literal["header"],
85
+ "format": Literal["JWT"],
86
+ "key": Literal["Authorization"],
87
+ "value": str,
88
+ },
89
+ )
90
+
91
+
92
+ BearerAuthSetting = TypedDict(
93
+ "BearerAuthSetting",
94
+ {
95
+ "type": Literal["bearer"],
96
+ "in": Literal["header"],
97
+ "key": Literal["Authorization"],
98
+ "value": str,
99
+ },
100
+ )
101
+
102
+
103
+ HTTPSignatureAuthSetting = TypedDict(
104
+ "HTTPSignatureAuthSetting",
105
+ {
106
+ "type": Literal["http-signature"],
107
+ "in": Literal["header"],
108
+ "key": Literal["Authorization"],
109
+ "value": None,
110
+ },
111
+ )
112
+
113
+
114
+ AuthSettings = TypedDict(
115
+ "AuthSettings",
116
+ {
117
+ "bearerSecurity": BearerFormatAuthSetting,
118
+ "cookieAuth": APIKeyAuthSetting,
119
+ },
120
+ total=False,
121
+ )
122
+
123
+
124
+ class HostSettingVariable(TypedDict):
125
+ description: str
126
+ default_value: str
127
+ enum_values: List[str]
128
+
129
+
130
+ class HostSetting(TypedDict):
131
+ url: str
132
+ description: str
133
+ variables: NotRequired[Dict[str, HostSettingVariable]]
134
+
135
+
136
+ class Configuration:
137
+ """This class contains various settings of the API client.
138
+
139
+ :param host: Base url.
140
+ :param ignore_operation_servers
141
+ Boolean to ignore operation servers for the API client.
142
+ Config will use `host` as the base url regardless of the operation servers.
143
+ :param api_key: Dict to store API key(s).
144
+ Each entry in the dict specifies an API key.
145
+ The dict key is the name of the security scheme in the OAS specification.
146
+ The dict value is the API key secret.
147
+ :param api_key_prefix: Dict to store API prefix (e.g. Bearer).
148
+ The dict key is the name of the security scheme in the OAS specification.
149
+ The dict value is an API key prefix when generating the auth data.
150
+ :param username: Username for HTTP basic authentication.
151
+ :param password: Password for HTTP basic authentication.
152
+ :param access_token: Access token.
153
+ :param server_index: Index to servers configuration.
154
+ :param server_variables: Mapping with string values to replace variables in
155
+ templated server configuration. The validation of enums is performed for
156
+ variables with defined enum values before.
157
+ :param server_operation_index: Mapping from operation ID to an index to server
158
+ configuration.
159
+ :param server_operation_variables: Mapping from operation ID to a mapping with
160
+ string values to replace variables in templated server configuration.
161
+ The validation of enums is performed for variables with defined enum
162
+ values before.
163
+ :param ssl_ca_cert: str - the path to a file of concatenated CA certificates
164
+ in PEM format.
165
+ :param retries: Number of retries for API requests.
166
+ :param ca_cert_data: verify the peer using concatenated CA certificate data
167
+ in PEM (str) or DER (bytes) format.
168
+ :param cert_file: the path to a client certificate file, for mTLS.
169
+ :param key_file: the path to a client key file, for mTLS.
170
+
171
+ :Example:
172
+
173
+ API Key Authentication Example.
174
+ Given the following security scheme in the OpenAPI specification:
175
+ components:
176
+ securitySchemes:
177
+ cookieAuth: # name for the security scheme
178
+ type: apiKey
179
+ in: cookie
180
+ name: JSESSIONID # cookie name
181
+
182
+ You can programmatically set the cookie:
183
+
184
+ conf = lunchmoney.Configuration(
185
+ api_key={'cookieAuth': 'abc123'}
186
+ api_key_prefix={'cookieAuth': 'JSESSIONID'}
187
+ )
188
+
189
+ The following cookie will be added to the HTTP request:
190
+ Cookie: JSESSIONID abc123
191
+ """
192
+
193
+ _default: ClassVar[Optional[Self]] = None
194
+
195
+ def __init__(
196
+ self,
197
+ host: Optional[str]=None,
198
+ api_key: Optional[Dict[str, str]]=None,
199
+ api_key_prefix: Optional[Dict[str, str]]=None,
200
+ username: Optional[str]=None,
201
+ password: Optional[str]=None,
202
+ access_token: Optional[str]=None,
203
+ server_index: Optional[int]=None,
204
+ server_variables: Optional[ServerVariablesT]=None,
205
+ server_operation_index: Optional[Dict[int, int]]=None,
206
+ server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None,
207
+ ignore_operation_servers: bool=False,
208
+ ssl_ca_cert: Optional[str]=None,
209
+ retries: Optional[int] = None,
210
+ ca_cert_data: Optional[Union[str, bytes]] = None,
211
+ cert_file: Optional[str]=None,
212
+ key_file: Optional[str]=None,
213
+ *,
214
+ debug: Optional[bool] = None,
215
+ ) -> None:
216
+ """Constructor
217
+ """
218
+ self._base_path = "https://api.lunchmoney.dev/v2" if host is None else host
219
+ """Default Base url
220
+ """
221
+ self.server_index = 0 if server_index is None and host is None else server_index
222
+ self.server_operation_index = server_operation_index or {}
223
+ """Default server index
224
+ """
225
+ self.server_variables = server_variables or {}
226
+ self.server_operation_variables = server_operation_variables or {}
227
+ """Default server variables
228
+ """
229
+ self.ignore_operation_servers = ignore_operation_servers
230
+ """Ignore operation servers
231
+ """
232
+ self.temp_folder_path = None
233
+ """Temp file folder for downloading files
234
+ """
235
+ # Authentication Settings
236
+ self.api_key = {}
237
+ if api_key:
238
+ self.api_key = api_key
239
+ """dict to store API key(s)
240
+ """
241
+ self.api_key_prefix = {}
242
+ if api_key_prefix:
243
+ self.api_key_prefix = api_key_prefix
244
+ """dict to store API prefix (e.g. Bearer)
245
+ """
246
+ self.refresh_api_key_hook = None
247
+ """function hook to refresh API key if expired
248
+ """
249
+ self.username = username
250
+ """Username for HTTP basic authentication
251
+ """
252
+ self.password = password
253
+ """Password for HTTP basic authentication
254
+ """
255
+ self.access_token = access_token
256
+ """Access token
257
+ """
258
+ self.logger = {}
259
+ """Logging Settings
260
+ """
261
+ self.logger["package_logger"] = logging.getLogger("lunchmoney")
262
+ self.logger["urllib3_logger"] = logging.getLogger("urllib3")
263
+ self.logger_format = '%(asctime)s %(levelname)s %(message)s'
264
+ """Log format
265
+ """
266
+ self.logger_stream_handler = None
267
+ """Log stream handler
268
+ """
269
+ self.logger_file_handler: Optional[FileHandler] = None
270
+ """Log file handler
271
+ """
272
+ self.logger_file = None
273
+ """Debug file location
274
+ """
275
+ if debug is not None:
276
+ self.debug = debug
277
+ else:
278
+ self.__debug = False
279
+ """Debug switch
280
+ """
281
+
282
+ self.verify_ssl = True
283
+ """SSL/TLS verification
284
+ Set this to false to skip verifying SSL certificate when calling API
285
+ from https server.
286
+ """
287
+ self.ssl_ca_cert = ssl_ca_cert
288
+ """Set this to customize the certificate file to verify the peer.
289
+ """
290
+ self.ca_cert_data = ca_cert_data
291
+ """Set this to verify the peer using PEM (str) or DER (bytes)
292
+ certificate data.
293
+ """
294
+ self.cert_file = cert_file
295
+ """client certificate file
296
+ """
297
+ self.key_file = key_file
298
+ """client key file
299
+ """
300
+ self.assert_hostname = None
301
+ """Set this to True/False to enable/disable SSL hostname verification.
302
+ """
303
+ self.tls_server_name = None
304
+ """SSL/TLS Server Name Indication (SNI)
305
+ Set this to the SNI value expected by the server.
306
+ """
307
+
308
+ self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
309
+ """urllib3 connection pool's maximum number of connections saved
310
+ per pool. urllib3 uses 1 connection as default value, but this is
311
+ not the best value when you are making a lot of possibly parallel
312
+ requests to the same host, which is often the case here.
313
+ cpu_count * 5 is used as default value to increase performance.
314
+ """
315
+
316
+ self.proxy: Optional[str] = None
317
+ """Proxy URL
318
+ """
319
+ self.proxy_headers = None
320
+ """Proxy headers
321
+ """
322
+ self.safe_chars_for_path_param = ''
323
+ """Safe chars for path_param
324
+ """
325
+ self.retries = retries
326
+ """Adding retries to override urllib3 default value 3
327
+ """
328
+ # Enable client side validation
329
+ self.client_side_validation = True
330
+
331
+ self.socket_options = None
332
+ """Options to pass down to the underlying urllib3 socket
333
+ """
334
+
335
+ self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
336
+ """datetime format
337
+ """
338
+
339
+ self.date_format = "%Y-%m-%d"
340
+ """date format
341
+ """
342
+
343
+ def __deepcopy__(self, memo: Dict[int, Any]) -> Self:
344
+ cls = self.__class__
345
+ result = cls.__new__(cls)
346
+ memo[id(self)] = result
347
+ for k, v in self.__dict__.items():
348
+ if k not in ('logger', 'logger_file_handler'):
349
+ setattr(result, k, copy.deepcopy(v, memo))
350
+ # shallow copy of loggers
351
+ result.logger = copy.copy(self.logger)
352
+ # use setters to configure loggers
353
+ result.logger_file = self.logger_file
354
+ result.debug = self.debug
355
+ return result
356
+
357
+ def __setattr__(self, name: str, value: Any) -> None:
358
+ object.__setattr__(self, name, value)
359
+
360
+ @classmethod
361
+ def set_default(cls, default: Optional[Self]) -> None:
362
+ """Set default instance of configuration.
363
+
364
+ It stores default configuration, which can be
365
+ returned by get_default_copy method.
366
+
367
+ :param default: object of Configuration
368
+ """
369
+ cls._default = default
370
+
371
+ @classmethod
372
+ def get_default_copy(cls) -> Self:
373
+ """Deprecated. Please use `get_default` instead.
374
+
375
+ Deprecated. Please use `get_default` instead.
376
+
377
+ :return: The configuration object.
378
+ """
379
+ return cls.get_default()
380
+
381
+ @classmethod
382
+ def get_default(cls) -> Self:
383
+ """Return the default configuration.
384
+
385
+ This method returns newly created, based on default constructor,
386
+ object of Configuration class or returns a copy of default
387
+ configuration.
388
+
389
+ :return: The configuration object.
390
+ """
391
+ if cls._default is None:
392
+ cls._default = cls()
393
+ return cls._default
394
+
395
+ @property
396
+ def logger_file(self) -> Optional[str]:
397
+ """The logger file.
398
+
399
+ If the logger_file is None, then add stream handler and remove file
400
+ handler. Otherwise, add file handler and remove stream handler.
401
+
402
+ :param value: The logger_file path.
403
+ :type: str
404
+ """
405
+ return self.__logger_file
406
+
407
+ @logger_file.setter
408
+ def logger_file(self, value: Optional[str]) -> None:
409
+ """The logger file.
410
+
411
+ If the logger_file is None, then add stream handler and remove file
412
+ handler. Otherwise, add file handler and remove stream handler.
413
+
414
+ :param value: The logger_file path.
415
+ :type: str
416
+ """
417
+ self.__logger_file = value
418
+ if self.__logger_file:
419
+ # If set logging file,
420
+ # then add file handler and remove stream handler.
421
+ self.logger_file_handler = logging.FileHandler(self.__logger_file)
422
+ self.logger_file_handler.setFormatter(self.logger_formatter)
423
+ for _, logger in self.logger.items():
424
+ logger.addHandler(self.logger_file_handler)
425
+
426
+ @property
427
+ def debug(self) -> bool:
428
+ """Debug status
429
+
430
+ :param value: The debug status, True or False.
431
+ :type: bool
432
+ """
433
+ return self.__debug
434
+
435
+ @debug.setter
436
+ def debug(self, value: bool) -> None:
437
+ """Debug status
438
+
439
+ :param value: The debug status, True or False.
440
+ :type: bool
441
+ """
442
+ self.__debug = value
443
+ if self.__debug:
444
+ # if debug status is True, turn on debug logging
445
+ for _, logger in self.logger.items():
446
+ logger.setLevel(logging.DEBUG)
447
+ # turn on httplib debug
448
+ httplib.HTTPConnection.debuglevel = 1
449
+ else:
450
+ # if debug status is False, turn off debug logging,
451
+ # setting log level to default `logging.WARNING`
452
+ for _, logger in self.logger.items():
453
+ logger.setLevel(logging.WARNING)
454
+ # turn off httplib debug
455
+ httplib.HTTPConnection.debuglevel = 0
456
+
457
+ @property
458
+ def logger_format(self) -> str:
459
+ """The logger format.
460
+
461
+ The logger_formatter will be updated when sets logger_format.
462
+
463
+ :param value: The format string.
464
+ :type: str
465
+ """
466
+ return self.__logger_format
467
+
468
+ @logger_format.setter
469
+ def logger_format(self, value: str) -> None:
470
+ """The logger format.
471
+
472
+ The logger_formatter will be updated when sets logger_format.
473
+
474
+ :param value: The format string.
475
+ :type: str
476
+ """
477
+ self.__logger_format = value
478
+ self.logger_formatter = logging.Formatter(self.__logger_format)
479
+
480
+ def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]:
481
+ """Gets API key (with prefix if set).
482
+
483
+ :param identifier: The identifier of apiKey.
484
+ :param alias: The alternative identifier of apiKey.
485
+ :return: The token for api key authentication.
486
+ """
487
+ if self.refresh_api_key_hook is not None:
488
+ self.refresh_api_key_hook(self)
489
+ key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
490
+ if key:
491
+ prefix = self.api_key_prefix.get(identifier)
492
+ if prefix:
493
+ return "%s %s" % (prefix, key)
494
+ else:
495
+ return key
496
+
497
+ return None
498
+
499
+ def get_basic_auth_token(self) -> Optional[str]:
500
+ """Gets HTTP basic authentication header (string).
501
+
502
+ :return: The token for basic HTTP authentication.
503
+ """
504
+ username = ""
505
+ if self.username is not None:
506
+ username = self.username
507
+ password = ""
508
+ if self.password is not None:
509
+ password = self.password
510
+ return urllib3.util.make_headers(
511
+ basic_auth=username + ':' + password
512
+ ).get('authorization')
513
+
514
+ def auth_settings(self)-> AuthSettings:
515
+ """Gets Auth Settings dict for api client.
516
+
517
+ :return: The Auth Settings information dict.
518
+ """
519
+ auth: AuthSettings = {}
520
+ if self.access_token is not None:
521
+ auth['bearerSecurity'] = {
522
+ 'type': 'bearer',
523
+ 'in': 'header',
524
+ 'format': 'JWT',
525
+ 'key': 'Authorization',
526
+ 'value': 'Bearer ' + self.access_token
527
+ }
528
+ if 'cookieAuth' in self.api_key:
529
+ auth['cookieAuth'] = {
530
+ 'type': 'api_key',
531
+ 'in': 'cookie',
532
+ 'key': '_lm_access_token',
533
+ 'value': self.get_api_key_with_prefix(
534
+ 'cookieAuth',
535
+ ),
536
+ }
537
+ return auth
538
+
539
+ def to_debug_report(self) -> str:
540
+ """Gets the essential information for debugging.
541
+
542
+ :return: The report for debugging.
543
+ """
544
+ return "Python SDK Debug Report:\n"\
545
+ "OS: {env}\n"\
546
+ "Python Version: {pyversion}\n"\
547
+ "Version of the API: 2.8.4\n"\
548
+ "SDK Package Version: 2.9.0".\
549
+ format(env=sys.platform, pyversion=sys.version)
550
+
551
+ def get_host_settings(self) -> List[HostSetting]:
552
+ """Gets an array of host settings
553
+
554
+ :return: An array of host settings
555
+ """
556
+ return [
557
+ {
558
+ 'url': "https://api.lunchmoney.dev/v2",
559
+ 'description': "v2 Lunch Money API Server - modifies real data!",
560
+ },
561
+ {
562
+ 'url': "https://mock.lunchmoney.dev/v2",
563
+ 'description': "Static Mock v2 Lunch Money API Server",
564
+ }
565
+ ]
566
+
567
+ def get_host_from_settings(
568
+ self,
569
+ index: Optional[int],
570
+ variables: Optional[ServerVariablesT]=None,
571
+ servers: Optional[List[HostSetting]]=None,
572
+ ) -> str:
573
+ """Gets host URL based on the index and variables
574
+ :param index: array index of the host settings
575
+ :param variables: hash of variable and the corresponding value
576
+ :param servers: an array of host settings or None
577
+ :return: URL based on host settings
578
+ """
579
+ if index is None:
580
+ return self._base_path
581
+
582
+ variables = {} if variables is None else variables
583
+ servers = self.get_host_settings() if servers is None else servers
584
+
585
+ try:
586
+ server = servers[index]
587
+ except IndexError:
588
+ raise ValueError(
589
+ "Invalid index {0} when selecting the host settings. "
590
+ "Must be less than {1}".format(index, len(servers)))
591
+
592
+ url = server['url']
593
+
594
+ # go through variables and replace placeholders
595
+ for variable_name, variable in server.get('variables', {}).items():
596
+ used_value = variables.get(
597
+ variable_name, variable['default_value'])
598
+
599
+ if 'enum_values' in variable \
600
+ and used_value not in variable['enum_values']:
601
+ raise ValueError(
602
+ "The variable `{0}` in the host URL has invalid value "
603
+ "{1}. Must be {2}.".format(
604
+ variable_name, variables[variable_name],
605
+ variable['enum_values']))
606
+
607
+ url = url.replace("{" + variable_name + "}", used_value)
608
+
609
+ return url
610
+
611
+ @property
612
+ def host(self) -> str:
613
+ """Return generated host."""
614
+ return self.get_host_from_settings(self.server_index, variables=self.server_variables)
615
+
616
+ @host.setter
617
+ def host(self, value: str) -> None:
618
+ """Fix base path."""
619
+ self._base_path = value
620
+ self.server_index = None