amazon-creatorsapi-python-sdk 1.0.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 (108) hide show
  1. amazon_creatorsapi_python_sdk-1.0.0.dist-info/METADATA +99 -0
  2. amazon_creatorsapi_python_sdk-1.0.0.dist-info/RECORD +108 -0
  3. amazon_creatorsapi_python_sdk-1.0.0.dist-info/WHEEL +5 -0
  4. amazon_creatorsapi_python_sdk-1.0.0.dist-info/licenses/LICENSE.txt +202 -0
  5. amazon_creatorsapi_python_sdk-1.0.0.dist-info/licenses/NOTICE.txt +2 -0
  6. amazon_creatorsapi_python_sdk-1.0.0.dist-info/top_level.txt +1 -0
  7. creatorsapi_python_sdk/__init__.py +127 -0
  8. creatorsapi_python_sdk/api/__init__.py +5 -0
  9. creatorsapi_python_sdk/api/default_api.py +2412 -0
  10. creatorsapi_python_sdk/api_client.py +912 -0
  11. creatorsapi_python_sdk/api_response.py +21 -0
  12. creatorsapi_python_sdk/auth/__init__.py +21 -0
  13. creatorsapi_python_sdk/auth/oauth2_config.py +123 -0
  14. creatorsapi_python_sdk/auth/oauth2_token_manager.py +120 -0
  15. creatorsapi_python_sdk/configuration.py +455 -0
  16. creatorsapi_python_sdk/exceptions.py +204 -0
  17. creatorsapi_python_sdk/models/__init__.py +110 -0
  18. creatorsapi_python_sdk/models/access_denied_exception_response_content.py +97 -0
  19. creatorsapi_python_sdk/models/access_denied_reason.py +45 -0
  20. creatorsapi_python_sdk/models/availability.py +44 -0
  21. creatorsapi_python_sdk/models/browse_node.py +116 -0
  22. creatorsapi_python_sdk/models/browse_node_ancestor.py +103 -0
  23. creatorsapi_python_sdk/models/browse_node_child.py +96 -0
  24. creatorsapi_python_sdk/models/browse_node_info.py +106 -0
  25. creatorsapi_python_sdk/models/browse_nodes_result.py +100 -0
  26. creatorsapi_python_sdk/models/by_line_info.py +111 -0
  27. creatorsapi_python_sdk/models/classifications.py +101 -0
  28. creatorsapi_python_sdk/models/condition.py +44 -0
  29. creatorsapi_python_sdk/models/content_info.py +113 -0
  30. creatorsapi_python_sdk/models/content_rating.py +96 -0
  31. creatorsapi_python_sdk/models/contributor.py +98 -0
  32. creatorsapi_python_sdk/models/customer_reviews.py +98 -0
  33. creatorsapi_python_sdk/models/deal_details.py +102 -0
  34. creatorsapi_python_sdk/models/delivery_flag.py +46 -0
  35. creatorsapi_python_sdk/models/dimension_based_attribute.py +111 -0
  36. creatorsapi_python_sdk/models/error_data.py +94 -0
  37. creatorsapi_python_sdk/models/external_ids.py +106 -0
  38. creatorsapi_python_sdk/models/feed.py +98 -0
  39. creatorsapi_python_sdk/models/get_browse_nodes_request_content.py +107 -0
  40. creatorsapi_python_sdk/models/get_browse_nodes_resource.py +44 -0
  41. creatorsapi_python_sdk/models/get_browse_nodes_response_content.py +106 -0
  42. creatorsapi_python_sdk/models/get_feed_request_content.py +93 -0
  43. creatorsapi_python_sdk/models/get_feed_response_content.py +92 -0
  44. creatorsapi_python_sdk/models/get_items_request_content.py +124 -0
  45. creatorsapi_python_sdk/models/get_items_resource.py +76 -0
  46. creatorsapi_python_sdk/models/get_items_response_content.py +106 -0
  47. creatorsapi_python_sdk/models/get_report_request_content.py +93 -0
  48. creatorsapi_python_sdk/models/get_report_response_content.py +92 -0
  49. creatorsapi_python_sdk/models/get_variations_request_content.py +135 -0
  50. creatorsapi_python_sdk/models/get_variations_resource.py +79 -0
  51. creatorsapi_python_sdk/models/get_variations_response_content.py +106 -0
  52. creatorsapi_python_sdk/models/image_size.py +96 -0
  53. creatorsapi_python_sdk/models/image_type.py +111 -0
  54. creatorsapi_python_sdk/models/images.py +105 -0
  55. creatorsapi_python_sdk/models/internal_server_exception_response_content.py +94 -0
  56. creatorsapi_python_sdk/models/item.py +138 -0
  57. creatorsapi_python_sdk/models/item_info.py +156 -0
  58. creatorsapi_python_sdk/models/items_result.py +100 -0
  59. creatorsapi_python_sdk/models/language_type.py +94 -0
  60. creatorsapi_python_sdk/models/languages.py +104 -0
  61. creatorsapi_python_sdk/models/list_feeds_response_content.py +100 -0
  62. creatorsapi_python_sdk/models/list_reports_response_content.py +100 -0
  63. creatorsapi_python_sdk/models/manufacture_info.py +106 -0
  64. creatorsapi_python_sdk/models/money.py +96 -0
  65. creatorsapi_python_sdk/models/multi_valued_attribute.py +96 -0
  66. creatorsapi_python_sdk/models/offer_availability_v2.py +98 -0
  67. creatorsapi_python_sdk/models/offer_condition_v2.py +96 -0
  68. creatorsapi_python_sdk/models/offer_listing_v2.py +133 -0
  69. creatorsapi_python_sdk/models/offer_loyalty_points_v2.py +92 -0
  70. creatorsapi_python_sdk/models/offer_merchant_info_v2.py +94 -0
  71. creatorsapi_python_sdk/models/offer_price_v2.py +113 -0
  72. creatorsapi_python_sdk/models/offer_saving_basis.py +101 -0
  73. creatorsapi_python_sdk/models/offer_savings.py +98 -0
  74. creatorsapi_python_sdk/models/offer_type.py +45 -0
  75. creatorsapi_python_sdk/models/offers_v2.py +100 -0
  76. creatorsapi_python_sdk/models/product_info.py +124 -0
  77. creatorsapi_python_sdk/models/rating.py +92 -0
  78. creatorsapi_python_sdk/models/refinement.py +104 -0
  79. creatorsapi_python_sdk/models/refinement_bin.py +94 -0
  80. creatorsapi_python_sdk/models/report_metadata.py +98 -0
  81. creatorsapi_python_sdk/models/resource_not_found_exception_response_content.py +98 -0
  82. creatorsapi_python_sdk/models/saving_basis_type.py +46 -0
  83. creatorsapi_python_sdk/models/search_items_request_content.py +242 -0
  84. creatorsapi_python_sdk/models/search_items_resource.py +77 -0
  85. creatorsapi_python_sdk/models/search_items_response_content.py +106 -0
  86. creatorsapi_python_sdk/models/search_refinements.py +110 -0
  87. creatorsapi_python_sdk/models/search_result.py +110 -0
  88. creatorsapi_python_sdk/models/single_boolean_valued_attribute.py +96 -0
  89. creatorsapi_python_sdk/models/single_integer_valued_attribute.py +96 -0
  90. creatorsapi_python_sdk/models/single_string_valued_attribute.py +96 -0
  91. creatorsapi_python_sdk/models/sort_by.py +48 -0
  92. creatorsapi_python_sdk/models/technical_info.py +102 -0
  93. creatorsapi_python_sdk/models/throttle_exception_response_content.py +98 -0
  94. creatorsapi_python_sdk/models/trade_in_info.py +98 -0
  95. creatorsapi_python_sdk/models/trade_in_price.py +96 -0
  96. creatorsapi_python_sdk/models/unauthorized_exception_reason.py +51 -0
  97. creatorsapi_python_sdk/models/unauthorized_exception_response_content.py +97 -0
  98. creatorsapi_python_sdk/models/unit_based_attribute.py +98 -0
  99. creatorsapi_python_sdk/models/validation_exception_field.py +94 -0
  100. creatorsapi_python_sdk/models/validation_exception_reason.py +48 -0
  101. creatorsapi_python_sdk/models/validation_exception_response_content.py +107 -0
  102. creatorsapi_python_sdk/models/variation_attribute.py +94 -0
  103. creatorsapi_python_sdk/models/variation_dimension.py +98 -0
  104. creatorsapi_python_sdk/models/variation_summary.py +104 -0
  105. creatorsapi_python_sdk/models/variations_result.py +106 -0
  106. creatorsapi_python_sdk/models/website_sales_rank.py +98 -0
  107. creatorsapi_python_sdk/py.typed +0 -0
  108. creatorsapi_python_sdk/rest.py +262 -0
@@ -0,0 +1,455 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License").
7
+ You may not use this file except in compliance with the License.
8
+ A copy of the License is located at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ or in the "license" file accompanying this file. This file is distributed
13
+ on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
14
+ express or implied. See the License for the specific language governing
15
+ permissions and limitations under the License.
16
+
17
+ """ # noqa: E501
18
+
19
+
20
+ import copy
21
+ import logging
22
+ from logging import FileHandler
23
+ import multiprocessing
24
+ import sys
25
+ from typing import Optional
26
+ import urllib3
27
+
28
+ import http.client as httplib
29
+
30
+ JSON_SCHEMA_VALIDATION_KEYWORDS = {
31
+ 'multipleOf', 'maximum', 'exclusiveMaximum',
32
+ 'minimum', 'exclusiveMinimum', 'maxLength',
33
+ 'minLength', 'pattern', 'maxItems', 'minItems'
34
+ }
35
+
36
+ class Configuration:
37
+ """This class contains various settings of the API client.
38
+
39
+ :param host: Base url.
40
+ :param ignore_operation_servers
41
+ Boolean to ignore operation servers for the API client.
42
+ Config will use `host` as the base url regardless of the operation servers.
43
+ :param api_key: Dict to store API key(s).
44
+ Each entry in the dict specifies an API key.
45
+ The dict key is the name of the security scheme in the OAS specification.
46
+ The dict value is the API key secret.
47
+ :param api_key_prefix: Dict to store API prefix (e.g. Bearer).
48
+ The dict key is the name of the security scheme in the OAS specification.
49
+ The dict value is an API key prefix when generating the auth data.
50
+ :param username: Username for HTTP basic authentication.
51
+ :param password: Password for HTTP basic authentication.
52
+ :param access_token: Access token.
53
+ :param server_index: Index to servers configuration.
54
+ :param server_variables: Mapping with string values to replace variables in
55
+ templated server configuration. The validation of enums is performed for
56
+ variables with defined enum values before.
57
+ :param server_operation_index: Mapping from operation ID to an index to server
58
+ configuration.
59
+ :param server_operation_variables: Mapping from operation ID to a mapping with
60
+ string values to replace variables in templated server configuration.
61
+ The validation of enums is performed for variables with defined enum
62
+ values before.
63
+ :param ssl_ca_cert: str - the path to a file of concatenated CA certificates
64
+ in PEM format.
65
+ :param retries: Number of retries for API requests.
66
+
67
+ """
68
+
69
+ _default = None
70
+
71
+ def __init__(self, host=None,
72
+ api_key=None, api_key_prefix=None,
73
+ username=None, password=None,
74
+ access_token=None,
75
+ server_index=None, server_variables=None,
76
+ server_operation_index=None, server_operation_variables=None,
77
+ ignore_operation_servers=False,
78
+ ssl_ca_cert=None,
79
+ retries=None,
80
+ *,
81
+ debug: Optional[bool] = None
82
+ ) -> None:
83
+ """Constructor
84
+ """
85
+ self._base_path = "http://localhost" if host is None else host
86
+ """Default Base url
87
+ """
88
+ self.server_index = 0 if server_index is None and host is None else server_index
89
+ self.server_operation_index = server_operation_index or {}
90
+ """Default server index
91
+ """
92
+ self.server_variables = server_variables or {}
93
+ self.server_operation_variables = server_operation_variables or {}
94
+ """Default server variables
95
+ """
96
+ self.ignore_operation_servers = ignore_operation_servers
97
+ """Ignore operation servers
98
+ """
99
+ self.temp_folder_path = None
100
+ """Temp file folder for downloading files
101
+ """
102
+ # Authentication Settings
103
+ self.api_key = {}
104
+ if api_key:
105
+ self.api_key = api_key
106
+ """dict to store API key(s)
107
+ """
108
+ self.api_key_prefix = {}
109
+ if api_key_prefix:
110
+ self.api_key_prefix = api_key_prefix
111
+ """dict to store API prefix (e.g. Bearer)
112
+ """
113
+ self.refresh_api_key_hook = None
114
+ """function hook to refresh API key if expired
115
+ """
116
+ self.username = username
117
+ """Username for HTTP basic authentication
118
+ """
119
+ self.password = password
120
+ """Password for HTTP basic authentication
121
+ """
122
+ self.access_token = access_token
123
+ """Access token
124
+ """
125
+ self.logger = {}
126
+ """Logging Settings
127
+ """
128
+ self.logger["package_logger"] = logging.getLogger("creatorsapi_python_sdk")
129
+ self.logger["urllib3_logger"] = logging.getLogger("urllib3")
130
+ self.logger_format = '%(asctime)s %(levelname)s %(message)s'
131
+ """Log format
132
+ """
133
+ self.logger_stream_handler = None
134
+ """Log stream handler
135
+ """
136
+ self.logger_file_handler: Optional[FileHandler] = None
137
+ """Log file handler
138
+ """
139
+ self.logger_file = None
140
+ """Debug file location
141
+ """
142
+ if debug is not None:
143
+ self.debug = debug
144
+ else:
145
+ self.__debug = False
146
+ """Debug switch
147
+ """
148
+
149
+ self.verify_ssl = True
150
+ """SSL/TLS verification
151
+ Set this to false to skip verifying SSL certificate when calling API
152
+ from https server.
153
+ """
154
+ self.ssl_ca_cert = ssl_ca_cert
155
+ """Set this to customize the certificate file to verify the peer.
156
+ """
157
+ self.cert_file = None
158
+ """client certificate file
159
+ """
160
+ self.key_file = None
161
+ """client key file
162
+ """
163
+ self.assert_hostname = None
164
+ """Set this to True/False to enable/disable SSL hostname verification.
165
+ """
166
+ self.tls_server_name = None
167
+ """SSL/TLS Server Name Indication (SNI)
168
+ Set this to the SNI value expected by the server.
169
+ """
170
+
171
+ self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
172
+ """urllib3 connection pool's maximum number of connections saved
173
+ per pool. urllib3 uses 1 connection as default value, but this is
174
+ not the best value when you are making a lot of possibly parallel
175
+ requests to the same host, which is often the case here.
176
+ cpu_count * 5 is used as default value to increase performance.
177
+ """
178
+
179
+ self.proxy: Optional[str] = None
180
+ """Proxy URL
181
+ """
182
+ self.proxy_headers = None
183
+ """Proxy headers
184
+ """
185
+ self.safe_chars_for_path_param = ''
186
+ """Safe chars for path_param
187
+ """
188
+ self.retries = retries
189
+ """Adding retries to override urllib3 default value 3
190
+ """
191
+ # Enable client side validation
192
+ self.client_side_validation = True
193
+
194
+ self.socket_options = None
195
+ """Options to pass down to the underlying urllib3 socket
196
+ """
197
+
198
+ self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
199
+ """datetime format
200
+ """
201
+
202
+ self.date_format = "%Y-%m-%d"
203
+ """date format
204
+ """
205
+
206
+ def __deepcopy__(self, memo):
207
+ cls = self.__class__
208
+ result = cls.__new__(cls)
209
+ memo[id(self)] = result
210
+ for k, v in self.__dict__.items():
211
+ if k not in ('logger', 'logger_file_handler'):
212
+ setattr(result, k, copy.deepcopy(v, memo))
213
+ # shallow copy of loggers
214
+ result.logger = copy.copy(self.logger)
215
+ # use setters to configure loggers
216
+ result.logger_file = self.logger_file
217
+ result.debug = self.debug
218
+ return result
219
+
220
+ def __setattr__(self, name, value):
221
+ object.__setattr__(self, name, value)
222
+
223
+ @classmethod
224
+ def set_default(cls, default):
225
+ """Set default instance of configuration.
226
+
227
+ It stores default configuration, which can be
228
+ returned by get_default_copy method.
229
+
230
+ :param default: object of Configuration
231
+ """
232
+ cls._default = default
233
+
234
+ @classmethod
235
+ def get_default_copy(cls):
236
+ """Deprecated. Please use `get_default` instead.
237
+
238
+ Deprecated. Please use `get_default` instead.
239
+
240
+ :return: The configuration object.
241
+ """
242
+ return cls.get_default()
243
+
244
+ @classmethod
245
+ def get_default(cls):
246
+ """Return the default configuration.
247
+
248
+ This method returns newly created, based on default constructor,
249
+ object of Configuration class or returns a copy of default
250
+ configuration.
251
+
252
+ :return: The configuration object.
253
+ """
254
+ if cls._default is None:
255
+ cls._default = Configuration()
256
+ return cls._default
257
+
258
+ @property
259
+ def logger_file(self):
260
+ """The logger file.
261
+
262
+ If the logger_file is None, then add stream handler and remove file
263
+ handler. Otherwise, add file handler and remove stream handler.
264
+
265
+ :param value: The logger_file path.
266
+ :type: str
267
+ """
268
+ return self.__logger_file
269
+
270
+ @logger_file.setter
271
+ def logger_file(self, value):
272
+ """The logger file.
273
+
274
+ If the logger_file is None, then add stream handler and remove file
275
+ handler. Otherwise, add file handler and remove stream handler.
276
+
277
+ :param value: The logger_file path.
278
+ :type: str
279
+ """
280
+ self.__logger_file = value
281
+ if self.__logger_file:
282
+ # If set logging file,
283
+ # then add file handler and remove stream handler.
284
+ self.logger_file_handler = logging.FileHandler(self.__logger_file)
285
+ self.logger_file_handler.setFormatter(self.logger_formatter)
286
+ for _, logger in self.logger.items():
287
+ logger.addHandler(self.logger_file_handler)
288
+
289
+ @property
290
+ def debug(self):
291
+ """Debug status
292
+
293
+ :param value: The debug status, True or False.
294
+ :type: bool
295
+ """
296
+ return self.__debug
297
+
298
+ @debug.setter
299
+ def debug(self, value):
300
+ """Debug status
301
+
302
+ :param value: The debug status, True or False.
303
+ :type: bool
304
+ """
305
+ self.__debug = value
306
+ if self.__debug:
307
+ # if debug status is True, turn on debug logging
308
+ for _, logger in self.logger.items():
309
+ logger.setLevel(logging.DEBUG)
310
+ # turn on httplib debug
311
+ httplib.HTTPConnection.debuglevel = 1
312
+ else:
313
+ # if debug status is False, turn off debug logging,
314
+ # setting log level to default `logging.WARNING`
315
+ for _, logger in self.logger.items():
316
+ logger.setLevel(logging.WARNING)
317
+ # turn off httplib debug
318
+ httplib.HTTPConnection.debuglevel = 0
319
+
320
+ @property
321
+ def logger_format(self):
322
+ """The logger format.
323
+
324
+ The logger_formatter will be updated when sets logger_format.
325
+
326
+ :param value: The format string.
327
+ :type: str
328
+ """
329
+ return self.__logger_format
330
+
331
+ @logger_format.setter
332
+ def logger_format(self, value):
333
+ """The logger format.
334
+
335
+ The logger_formatter will be updated when sets logger_format.
336
+
337
+ :param value: The format string.
338
+ :type: str
339
+ """
340
+ self.__logger_format = value
341
+ self.logger_formatter = logging.Formatter(self.__logger_format)
342
+
343
+ def get_api_key_with_prefix(self, identifier, alias=None):
344
+ """Gets API key (with prefix if set).
345
+
346
+ :param identifier: The identifier of apiKey.
347
+ :param alias: The alternative identifier of apiKey.
348
+ :return: The token for api key authentication.
349
+ """
350
+ if self.refresh_api_key_hook is not None:
351
+ self.refresh_api_key_hook(self)
352
+ key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
353
+ if key:
354
+ prefix = self.api_key_prefix.get(identifier)
355
+ if prefix:
356
+ return "%s %s" % (prefix, key)
357
+ else:
358
+ return key
359
+
360
+ def get_basic_auth_token(self):
361
+ """Gets HTTP basic authentication header (string).
362
+
363
+ :return: The token for basic HTTP authentication.
364
+ """
365
+ username = ""
366
+ if self.username is not None:
367
+ username = self.username
368
+ password = ""
369
+ if self.password is not None:
370
+ password = self.password
371
+ return urllib3.util.make_headers(
372
+ basic_auth=username + ':' + password
373
+ ).get('authorization')
374
+
375
+ def auth_settings(self):
376
+ """Gets Auth Settings dict for api client.
377
+
378
+ :return: The Auth Settings information dict.
379
+ """
380
+ auth = {}
381
+ return auth
382
+
383
+ def to_debug_report(self):
384
+ """Gets the essential information for debugging.
385
+
386
+ :return: The report for debugging.
387
+ """
388
+ return "Python SDK Debug Report:\n"\
389
+ "OS: {env}\n"\
390
+ "Python Version: {pyversion}\n"\
391
+ "Version of the API: 2024-08-16\n"\
392
+ "SDK Package Version: 1.0.0".\
393
+ format(env=sys.platform, pyversion=sys.version)
394
+
395
+ def get_host_settings(self):
396
+ """Gets an array of host settings
397
+
398
+ :return: An array of host settings
399
+ """
400
+ return [
401
+ {
402
+ 'url': "",
403
+ 'description': "No description provided",
404
+ }
405
+ ]
406
+
407
+ def get_host_from_settings(self, index, variables=None, servers=None):
408
+ """Gets host URL based on the index and variables
409
+ :param index: array index of the host settings
410
+ :param variables: hash of variable and the corresponding value
411
+ :param servers: an array of host settings or None
412
+ :return: URL based on host settings
413
+ """
414
+ if index is None:
415
+ return self._base_path
416
+
417
+ variables = {} if variables is None else variables
418
+ servers = self.get_host_settings() if servers is None else servers
419
+
420
+ try:
421
+ server = servers[index]
422
+ except IndexError:
423
+ raise ValueError(
424
+ "Invalid index {0} when selecting the host settings. "
425
+ "Must be less than {1}".format(index, len(servers)))
426
+
427
+ url = server['url']
428
+
429
+ # go through variables and replace placeholders
430
+ for variable_name, variable in server.get('variables', {}).items():
431
+ used_value = variables.get(
432
+ variable_name, variable['default_value'])
433
+
434
+ if 'enum_values' in variable \
435
+ and used_value not in variable['enum_values']:
436
+ raise ValueError(
437
+ "The variable `{0}` in the host URL has invalid value "
438
+ "{1}. Must be {2}.".format(
439
+ variable_name, variables[variable_name],
440
+ variable['enum_values']))
441
+
442
+ url = url.replace("{" + variable_name + "}", used_value)
443
+
444
+ return url
445
+
446
+ @property
447
+ def host(self):
448
+ """Return generated host."""
449
+ return self.get_host_from_settings(self.server_index, variables=self.server_variables)
450
+
451
+ @host.setter
452
+ def host(self, value):
453
+ """Fix base path."""
454
+ self._base_path = value
455
+ self.server_index = None
@@ -0,0 +1,204 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License").
7
+ You may not use this file except in compliance with the License.
8
+ A copy of the License is located at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ or in the "license" file accompanying this file. This file is distributed
13
+ on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
14
+ express or implied. See the License for the specific language governing
15
+ permissions and limitations under the License.
16
+
17
+ """ # noqa: E501
18
+
19
+ from typing import Any, Optional
20
+ from typing_extensions import Self
21
+
22
+ class OpenApiException(Exception):
23
+ """The base exception class for all OpenAPIExceptions"""
24
+
25
+
26
+ class ApiTypeError(OpenApiException, TypeError):
27
+ def __init__(self, msg, path_to_item=None, valid_classes=None,
28
+ key_type=None) -> None:
29
+ """ Raises an exception for TypeErrors
30
+
31
+ Args:
32
+ msg (str): the exception message
33
+
34
+ Keyword Args:
35
+ path_to_item (list): a list of keys an indices to get to the
36
+ current_item
37
+ None if unset
38
+ valid_classes (tuple): the primitive classes that current item
39
+ should be an instance of
40
+ None if unset
41
+ key_type (bool): False if our value is a value in a dict
42
+ True if it is a key in a dict
43
+ False if our item is an item in a list
44
+ None if unset
45
+ """
46
+ self.path_to_item = path_to_item
47
+ self.valid_classes = valid_classes
48
+ self.key_type = key_type
49
+ full_msg = msg
50
+ if path_to_item:
51
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
52
+ super(ApiTypeError, self).__init__(full_msg)
53
+
54
+
55
+ class ApiValueError(OpenApiException, ValueError):
56
+ def __init__(self, msg, path_to_item=None) -> None:
57
+ """
58
+ Args:
59
+ msg (str): the exception message
60
+
61
+ Keyword Args:
62
+ path_to_item (list) the path to the exception in the
63
+ received_data dict. None if unset
64
+ """
65
+
66
+ self.path_to_item = path_to_item
67
+ full_msg = msg
68
+ if path_to_item:
69
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
70
+ super(ApiValueError, self).__init__(full_msg)
71
+
72
+
73
+ class ApiAttributeError(OpenApiException, AttributeError):
74
+ def __init__(self, msg, path_to_item=None) -> None:
75
+ """
76
+ Raised when an attribute reference or assignment fails.
77
+
78
+ Args:
79
+ msg (str): the exception message
80
+
81
+ Keyword Args:
82
+ path_to_item (None/list) the path to the exception in the
83
+ received_data dict
84
+ """
85
+ self.path_to_item = path_to_item
86
+ full_msg = msg
87
+ if path_to_item:
88
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
89
+ super(ApiAttributeError, self).__init__(full_msg)
90
+
91
+
92
+ class ApiKeyError(OpenApiException, KeyError):
93
+ def __init__(self, msg, path_to_item=None) -> None:
94
+ """
95
+ Args:
96
+ msg (str): the exception message
97
+
98
+ Keyword Args:
99
+ path_to_item (None/list) the path to the exception in the
100
+ received_data dict
101
+ """
102
+ self.path_to_item = path_to_item
103
+ full_msg = msg
104
+ if path_to_item:
105
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
106
+ super(ApiKeyError, self).__init__(full_msg)
107
+
108
+
109
+ class ApiException(OpenApiException):
110
+
111
+ def __init__(
112
+ self,
113
+ status=None,
114
+ reason=None,
115
+ http_resp=None,
116
+ *,
117
+ body: Optional[str] = None,
118
+ data: Optional[Any] = None,
119
+ ) -> None:
120
+ self.status = status
121
+ self.reason = reason
122
+ self.body = body
123
+ self.data = data
124
+ self.headers = None
125
+
126
+ if http_resp:
127
+ if self.status is None:
128
+ self.status = http_resp.status
129
+ if self.reason is None:
130
+ self.reason = http_resp.reason
131
+ if self.body is None:
132
+ try:
133
+ self.body = http_resp.data.decode('utf-8')
134
+ except Exception:
135
+ pass
136
+ self.headers = http_resp.getheaders()
137
+
138
+ @classmethod
139
+ def from_response(
140
+ cls,
141
+ *,
142
+ http_resp,
143
+ body: Optional[str],
144
+ data: Optional[Any],
145
+ ) -> Self:
146
+ if http_resp.status == 400:
147
+ raise BadRequestException(http_resp=http_resp, body=body, data=data)
148
+
149
+ if http_resp.status == 401:
150
+ raise UnauthorizedException(http_resp=http_resp, body=body, data=data)
151
+
152
+ if http_resp.status == 403:
153
+ raise ForbiddenException(http_resp=http_resp, body=body, data=data)
154
+
155
+ if http_resp.status == 404:
156
+ raise NotFoundException(http_resp=http_resp, body=body, data=data)
157
+
158
+ if 500 <= http_resp.status <= 599:
159
+ raise ServiceException(http_resp=http_resp, body=body, data=data)
160
+ raise ApiException(http_resp=http_resp, body=body, data=data)
161
+
162
+ def __str__(self):
163
+ """Custom error messages for exception"""
164
+ error_message = "({0})\n"\
165
+ "Reason: {1}\n".format(self.status, self.reason)
166
+ if self.headers:
167
+ error_message += "HTTP response headers: {0}\n".format(
168
+ self.headers)
169
+
170
+ if self.data or self.body:
171
+ error_message += "HTTP response body: {0}\n".format(self.data or self.body)
172
+
173
+ return error_message
174
+
175
+
176
+ class BadRequestException(ApiException):
177
+ pass
178
+
179
+
180
+ class NotFoundException(ApiException):
181
+ pass
182
+
183
+
184
+ class UnauthorizedException(ApiException):
185
+ pass
186
+
187
+
188
+ class ForbiddenException(ApiException):
189
+ pass
190
+
191
+
192
+ class ServiceException(ApiException):
193
+ pass
194
+
195
+
196
+ def render_path(path_to_item):
197
+ """Returns a string representation of a path"""
198
+ result = ""
199
+ for pth in path_to_item:
200
+ if isinstance(pth, int):
201
+ result += "[{0}]".format(pth)
202
+ else:
203
+ result += "['{0}']".format(pth)
204
+ return result