graphscope-flex 0.27.0__4-py2.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 (77) hide show
  1. graphscope/flex/rest/__init__.py +97 -0
  2. graphscope/flex/rest/api/__init__.py +12 -0
  3. graphscope/flex/rest/api/alert_api.py +2780 -0
  4. graphscope/flex/rest/api/data_source_api.py +1173 -0
  5. graphscope/flex/rest/api/deployment_api.py +528 -0
  6. graphscope/flex/rest/api/graph_api.py +2803 -0
  7. graphscope/flex/rest/api/job_api.py +1356 -0
  8. graphscope/flex/rest/api/service_api.py +1311 -0
  9. graphscope/flex/rest/api/stored_procedure_api.py +1449 -0
  10. graphscope/flex/rest/api/utils_api.py +309 -0
  11. graphscope/flex/rest/api_client.py +759 -0
  12. graphscope/flex/rest/api_response.py +21 -0
  13. graphscope/flex/rest/configuration.py +437 -0
  14. graphscope/flex/rest/exceptions.py +200 -0
  15. graphscope/flex/rest/models/__init__.py +73 -0
  16. graphscope/flex/rest/models/base_edge_type.py +102 -0
  17. graphscope/flex/rest/models/base_edge_type_vertex_type_pair_relations_inner.py +105 -0
  18. graphscope/flex/rest/models/base_edge_type_vertex_type_pair_relations_inner_x_csr_params.py +98 -0
  19. graphscope/flex/rest/models/base_property_meta.py +105 -0
  20. graphscope/flex/rest/models/base_vertex_type.py +96 -0
  21. graphscope/flex/rest/models/base_vertex_type_x_csr_params.py +88 -0
  22. graphscope/flex/rest/models/column_mapping.py +94 -0
  23. graphscope/flex/rest/models/column_mapping_column.py +90 -0
  24. graphscope/flex/rest/models/create_alert_receiver_request.py +103 -0
  25. graphscope/flex/rest/models/create_alert_rule_request.py +112 -0
  26. graphscope/flex/rest/models/create_dataloading_job_response.py +88 -0
  27. graphscope/flex/rest/models/create_edge_type.py +114 -0
  28. graphscope/flex/rest/models/create_graph_request.py +106 -0
  29. graphscope/flex/rest/models/create_graph_response.py +88 -0
  30. graphscope/flex/rest/models/create_graph_schema_request.py +106 -0
  31. graphscope/flex/rest/models/create_property_meta.py +100 -0
  32. graphscope/flex/rest/models/create_stored_proc_request.py +101 -0
  33. graphscope/flex/rest/models/create_stored_proc_response.py +88 -0
  34. graphscope/flex/rest/models/create_vertex_type.py +108 -0
  35. graphscope/flex/rest/models/dataloading_job_config.py +136 -0
  36. graphscope/flex/rest/models/dataloading_job_config_edges_inner.py +92 -0
  37. graphscope/flex/rest/models/dataloading_job_config_loading_config.py +104 -0
  38. graphscope/flex/rest/models/dataloading_job_config_loading_config_format.py +90 -0
  39. graphscope/flex/rest/models/dataloading_job_config_vertices_inner.py +88 -0
  40. graphscope/flex/rest/models/edge_mapping.py +122 -0
  41. graphscope/flex/rest/models/edge_mapping_type_triplet.py +92 -0
  42. graphscope/flex/rest/models/error.py +90 -0
  43. graphscope/flex/rest/models/get_alert_message_response.py +123 -0
  44. graphscope/flex/rest/models/get_alert_receiver_response.py +107 -0
  45. graphscope/flex/rest/models/get_alert_rule_response.py +114 -0
  46. graphscope/flex/rest/models/get_edge_type.py +116 -0
  47. graphscope/flex/rest/models/get_graph_response.py +126 -0
  48. graphscope/flex/rest/models/get_graph_schema_response.py +106 -0
  49. graphscope/flex/rest/models/get_property_meta.py +102 -0
  50. graphscope/flex/rest/models/get_stored_proc_response.py +128 -0
  51. graphscope/flex/rest/models/get_vertex_type.py +110 -0
  52. graphscope/flex/rest/models/gs_data_type.py +138 -0
  53. graphscope/flex/rest/models/job_status.py +107 -0
  54. graphscope/flex/rest/models/long_text.py +93 -0
  55. graphscope/flex/rest/models/node_status.py +94 -0
  56. graphscope/flex/rest/models/parameter.py +94 -0
  57. graphscope/flex/rest/models/primitive_type.py +95 -0
  58. graphscope/flex/rest/models/running_deployment_info.py +128 -0
  59. graphscope/flex/rest/models/running_deployment_status.py +105 -0
  60. graphscope/flex/rest/models/running_deployment_status_nodes_inner.py +124 -0
  61. graphscope/flex/rest/models/schema_mapping.py +106 -0
  62. graphscope/flex/rest/models/service_status.py +105 -0
  63. graphscope/flex/rest/models/service_status_sdk_endpoints.py +94 -0
  64. graphscope/flex/rest/models/start_service_request.py +88 -0
  65. graphscope/flex/rest/models/stored_procedure_meta.py +124 -0
  66. graphscope/flex/rest/models/string_type.py +92 -0
  67. graphscope/flex/rest/models/string_type_string.py +124 -0
  68. graphscope/flex/rest/models/update_alert_message_status_request.py +97 -0
  69. graphscope/flex/rest/models/update_stored_proc_request.py +88 -0
  70. graphscope/flex/rest/models/upload_file_response.py +88 -0
  71. graphscope/flex/rest/models/vertex_mapping.py +100 -0
  72. graphscope/flex/rest/py.typed +0 -0
  73. graphscope/flex/rest/rest.py +256 -0
  74. graphscope_flex-0.27.0.dist-info/METADATA +17 -0
  75. graphscope_flex-0.27.0.dist-info/RECORD +77 -0
  76. graphscope_flex-0.27.0.dist-info/WHEEL +6 -0
  77. graphscope_flex-0.27.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,437 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ GraphScope FLEX HTTP SERVICE API
5
+
6
+ This is a specification for GraphScope FLEX HTTP service based on the OpenAPI 3.0 specification. You can find out more details about specification at [doc](https://swagger.io/specification/v3/). Some useful links: - [GraphScope Repository](https://github.com/alibaba/GraphScope) - [The Source API definition for GraphScope Interactive](https://github.com/GraphScope/portal/tree/main/httpservice)
7
+
8
+ The version of the OpenAPI document: 1.0.0
9
+ Contact: graphscope@alibaba-inc.com
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 logging
18
+ from logging import FileHandler
19
+ import multiprocessing
20
+ import sys
21
+ from typing import Optional
22
+ import urllib3
23
+
24
+ import http.client as httplib
25
+
26
+ JSON_SCHEMA_VALIDATION_KEYWORDS = {
27
+ 'multipleOf', 'maximum', 'exclusiveMaximum',
28
+ 'minimum', 'exclusiveMinimum', 'maxLength',
29
+ 'minLength', 'pattern', 'maxItems', 'minItems'
30
+ }
31
+
32
+ class Configuration:
33
+ """This class contains various settings of the API client.
34
+
35
+ :param host: Base url.
36
+ :param api_key: Dict to store API key(s).
37
+ Each entry in the dict specifies an API key.
38
+ The dict key is the name of the security scheme in the OAS specification.
39
+ The dict value is the API key secret.
40
+ :param api_key_prefix: Dict to store API prefix (e.g. Bearer).
41
+ The dict key is the name of the security scheme in the OAS specification.
42
+ The dict value is an API key prefix when generating the auth data.
43
+ :param username: Username for HTTP basic authentication.
44
+ :param password: Password for HTTP basic authentication.
45
+ :param access_token: Access token.
46
+ :param server_index: Index to servers configuration.
47
+ :param server_variables: Mapping with string values to replace variables in
48
+ templated server configuration. The validation of enums is performed for
49
+ variables with defined enum values before.
50
+ :param server_operation_index: Mapping from operation ID to an index to server
51
+ configuration.
52
+ :param server_operation_variables: Mapping from operation ID to a mapping with
53
+ string values to replace variables in templated server configuration.
54
+ The validation of enums is performed for variables with defined enum
55
+ values before.
56
+ :param ssl_ca_cert: str - the path to a file of concatenated CA certificates
57
+ in PEM format.
58
+
59
+ """
60
+
61
+ _default = None
62
+
63
+ def __init__(self, host=None,
64
+ api_key=None, api_key_prefix=None,
65
+ username=None, password=None,
66
+ access_token=None,
67
+ server_index=None, server_variables=None,
68
+ server_operation_index=None, server_operation_variables=None,
69
+ ssl_ca_cert=None,
70
+ ) -> None:
71
+ """Constructor
72
+ """
73
+ self._base_path = "http://localhost" if host is None else host
74
+ """Default Base url
75
+ """
76
+ self.server_index = 0 if server_index is None and host is None else server_index
77
+ self.server_operation_index = server_operation_index or {}
78
+ """Default server index
79
+ """
80
+ self.server_variables = server_variables or {}
81
+ self.server_operation_variables = server_operation_variables or {}
82
+ """Default server variables
83
+ """
84
+ self.temp_folder_path = None
85
+ """Temp file folder for downloading files
86
+ """
87
+ # Authentication Settings
88
+ self.api_key = {}
89
+ if api_key:
90
+ self.api_key = api_key
91
+ """dict to store API key(s)
92
+ """
93
+ self.api_key_prefix = {}
94
+ if api_key_prefix:
95
+ self.api_key_prefix = api_key_prefix
96
+ """dict to store API prefix (e.g. Bearer)
97
+ """
98
+ self.refresh_api_key_hook = None
99
+ """function hook to refresh API key if expired
100
+ """
101
+ self.username = username
102
+ """Username for HTTP basic authentication
103
+ """
104
+ self.password = password
105
+ """Password for HTTP basic authentication
106
+ """
107
+ self.access_token = access_token
108
+ """Access token
109
+ """
110
+ self.logger = {}
111
+ """Logging Settings
112
+ """
113
+ self.logger["package_logger"] = logging.getLogger("graphscope.flex.rest")
114
+ self.logger["urllib3_logger"] = logging.getLogger("urllib3")
115
+ self.logger_format = '%(asctime)s %(levelname)s %(message)s'
116
+ """Log format
117
+ """
118
+ self.logger_stream_handler = None
119
+ """Log stream handler
120
+ """
121
+ self.logger_file_handler: Optional[FileHandler] = None
122
+ """Log file handler
123
+ """
124
+ self.logger_file = None
125
+ """Debug file location
126
+ """
127
+ self.debug = False
128
+ """Debug switch
129
+ """
130
+
131
+ self.verify_ssl = True
132
+ """SSL/TLS verification
133
+ Set this to false to skip verifying SSL certificate when calling API
134
+ from https server.
135
+ """
136
+ self.ssl_ca_cert = ssl_ca_cert
137
+ """Set this to customize the certificate file to verify the peer.
138
+ """
139
+ self.cert_file = None
140
+ """client certificate file
141
+ """
142
+ self.key_file = None
143
+ """client key file
144
+ """
145
+ self.assert_hostname = None
146
+ """Set this to True/False to enable/disable SSL hostname verification.
147
+ """
148
+ self.tls_server_name = None
149
+ """SSL/TLS Server Name Indication (SNI)
150
+ Set this to the SNI value expected by the server.
151
+ """
152
+
153
+ self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
154
+ """urllib3 connection pool's maximum number of connections saved
155
+ per pool. urllib3 uses 1 connection as default value, but this is
156
+ not the best value when you are making a lot of possibly parallel
157
+ requests to the same host, which is often the case here.
158
+ cpu_count * 5 is used as default value to increase performance.
159
+ """
160
+
161
+ self.proxy: Optional[str] = None
162
+ """Proxy URL
163
+ """
164
+ self.proxy_headers = None
165
+ """Proxy headers
166
+ """
167
+ self.safe_chars_for_path_param = ''
168
+ """Safe chars for path_param
169
+ """
170
+ self.retries = None
171
+ """Adding retries to override urllib3 default value 3
172
+ """
173
+ # Enable client side validation
174
+ self.client_side_validation = True
175
+
176
+ self.socket_options = None
177
+ """Options to pass down to the underlying urllib3 socket
178
+ """
179
+
180
+ self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
181
+ """datetime format
182
+ """
183
+
184
+ self.date_format = "%Y-%m-%d"
185
+ """date format
186
+ """
187
+
188
+ def __deepcopy__(self, memo):
189
+ cls = self.__class__
190
+ result = cls.__new__(cls)
191
+ memo[id(self)] = result
192
+ for k, v in self.__dict__.items():
193
+ if k not in ('logger', 'logger_file_handler'):
194
+ setattr(result, k, copy.deepcopy(v, memo))
195
+ # shallow copy of loggers
196
+ result.logger = copy.copy(self.logger)
197
+ # use setters to configure loggers
198
+ result.logger_file = self.logger_file
199
+ result.debug = self.debug
200
+ return result
201
+
202
+ def __setattr__(self, name, value):
203
+ object.__setattr__(self, name, value)
204
+
205
+ @classmethod
206
+ def set_default(cls, default):
207
+ """Set default instance of configuration.
208
+
209
+ It stores default configuration, which can be
210
+ returned by get_default_copy method.
211
+
212
+ :param default: object of Configuration
213
+ """
214
+ cls._default = default
215
+
216
+ @classmethod
217
+ def get_default_copy(cls):
218
+ """Deprecated. Please use `get_default` instead.
219
+
220
+ Deprecated. Please use `get_default` instead.
221
+
222
+ :return: The configuration object.
223
+ """
224
+ return cls.get_default()
225
+
226
+ @classmethod
227
+ def get_default(cls):
228
+ """Return the default configuration.
229
+
230
+ This method returns newly created, based on default constructor,
231
+ object of Configuration class or returns a copy of default
232
+ configuration.
233
+
234
+ :return: The configuration object.
235
+ """
236
+ if cls._default is None:
237
+ cls._default = Configuration()
238
+ return cls._default
239
+
240
+ @property
241
+ def logger_file(self):
242
+ """The logger file.
243
+
244
+ If the logger_file is None, then add stream handler and remove file
245
+ handler. Otherwise, add file handler and remove stream handler.
246
+
247
+ :param value: The logger_file path.
248
+ :type: str
249
+ """
250
+ return self.__logger_file
251
+
252
+ @logger_file.setter
253
+ def logger_file(self, value):
254
+ """The logger file.
255
+
256
+ If the logger_file is None, then add stream handler and remove file
257
+ handler. Otherwise, add file handler and remove stream handler.
258
+
259
+ :param value: The logger_file path.
260
+ :type: str
261
+ """
262
+ self.__logger_file = value
263
+ if self.__logger_file:
264
+ # If set logging file,
265
+ # then add file handler and remove stream handler.
266
+ self.logger_file_handler = logging.FileHandler(self.__logger_file)
267
+ self.logger_file_handler.setFormatter(self.logger_formatter)
268
+ for _, logger in self.logger.items():
269
+ logger.addHandler(self.logger_file_handler)
270
+
271
+ @property
272
+ def debug(self):
273
+ """Debug status
274
+
275
+ :param value: The debug status, True or False.
276
+ :type: bool
277
+ """
278
+ return self.__debug
279
+
280
+ @debug.setter
281
+ def debug(self, value):
282
+ """Debug status
283
+
284
+ :param value: The debug status, True or False.
285
+ :type: bool
286
+ """
287
+ self.__debug = value
288
+ if self.__debug:
289
+ # if debug status is True, turn on debug logging
290
+ for _, logger in self.logger.items():
291
+ logger.setLevel(logging.DEBUG)
292
+ # turn on httplib debug
293
+ httplib.HTTPConnection.debuglevel = 1
294
+ else:
295
+ # if debug status is False, turn off debug logging,
296
+ # setting log level to default `logging.WARNING`
297
+ for _, logger in self.logger.items():
298
+ logger.setLevel(logging.WARNING)
299
+ # turn off httplib debug
300
+ httplib.HTTPConnection.debuglevel = 0
301
+
302
+ @property
303
+ def logger_format(self):
304
+ """The logger format.
305
+
306
+ The logger_formatter will be updated when sets logger_format.
307
+
308
+ :param value: The format string.
309
+ :type: str
310
+ """
311
+ return self.__logger_format
312
+
313
+ @logger_format.setter
314
+ def logger_format(self, value):
315
+ """The logger format.
316
+
317
+ The logger_formatter will be updated when sets logger_format.
318
+
319
+ :param value: The format string.
320
+ :type: str
321
+ """
322
+ self.__logger_format = value
323
+ self.logger_formatter = logging.Formatter(self.__logger_format)
324
+
325
+ def get_api_key_with_prefix(self, identifier, alias=None):
326
+ """Gets API key (with prefix if set).
327
+
328
+ :param identifier: The identifier of apiKey.
329
+ :param alias: The alternative identifier of apiKey.
330
+ :return: The token for api key authentication.
331
+ """
332
+ if self.refresh_api_key_hook is not None:
333
+ self.refresh_api_key_hook(self)
334
+ key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
335
+ if key:
336
+ prefix = self.api_key_prefix.get(identifier)
337
+ if prefix:
338
+ return "%s %s" % (prefix, key)
339
+ else:
340
+ return key
341
+
342
+ def get_basic_auth_token(self):
343
+ """Gets HTTP basic authentication header (string).
344
+
345
+ :return: The token for basic HTTP authentication.
346
+ """
347
+ username = ""
348
+ if self.username is not None:
349
+ username = self.username
350
+ password = ""
351
+ if self.password is not None:
352
+ password = self.password
353
+ return urllib3.util.make_headers(
354
+ basic_auth=username + ':' + password
355
+ ).get('authorization')
356
+
357
+ def auth_settings(self):
358
+ """Gets Auth Settings dict for api client.
359
+
360
+ :return: The Auth Settings information dict.
361
+ """
362
+ auth = {}
363
+ return auth
364
+
365
+ def to_debug_report(self):
366
+ """Gets the essential information for debugging.
367
+
368
+ :return: The report for debugging.
369
+ """
370
+ return "Python SDK Debug Report:\n"\
371
+ "OS: {env}\n"\
372
+ "Python Version: {pyversion}\n"\
373
+ "Version of the API: 1.0.0\n"\
374
+ "SDK Package Version: 1.0.0".\
375
+ format(env=sys.platform, pyversion=sys.version)
376
+
377
+ def get_host_settings(self):
378
+ """Gets an array of host settings
379
+
380
+ :return: An array of host settings
381
+ """
382
+ return [
383
+ {
384
+ 'url': "",
385
+ 'description': "No description provided",
386
+ }
387
+ ]
388
+
389
+ def get_host_from_settings(self, index, variables=None, servers=None):
390
+ """Gets host URL based on the index and variables
391
+ :param index: array index of the host settings
392
+ :param variables: hash of variable and the corresponding value
393
+ :param servers: an array of host settings or None
394
+ :return: URL based on host settings
395
+ """
396
+ if index is None:
397
+ return self._base_path
398
+
399
+ variables = {} if variables is None else variables
400
+ servers = self.get_host_settings() if servers is None else servers
401
+
402
+ try:
403
+ server = servers[index]
404
+ except IndexError:
405
+ raise ValueError(
406
+ "Invalid index {0} when selecting the host settings. "
407
+ "Must be less than {1}".format(index, len(servers)))
408
+
409
+ url = server['url']
410
+
411
+ # go through variables and replace placeholders
412
+ for variable_name, variable in server.get('variables', {}).items():
413
+ used_value = variables.get(
414
+ variable_name, variable['default_value'])
415
+
416
+ if 'enum_values' in variable \
417
+ and used_value not in variable['enum_values']:
418
+ raise ValueError(
419
+ "The variable `{0}` in the host URL has invalid value "
420
+ "{1}. Must be {2}.".format(
421
+ variable_name, variables[variable_name],
422
+ variable['enum_values']))
423
+
424
+ url = url.replace("{" + variable_name + "}", used_value)
425
+
426
+ return url
427
+
428
+ @property
429
+ def host(self):
430
+ """Return generated host."""
431
+ return self.get_host_from_settings(self.server_index, variables=self.server_variables)
432
+
433
+ @host.setter
434
+ def host(self, value):
435
+ """Fix base path."""
436
+ self._base_path = value
437
+ self.server_index = None
@@ -0,0 +1,200 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ GraphScope FLEX HTTP SERVICE API
5
+
6
+ This is a specification for GraphScope FLEX HTTP service based on the OpenAPI 3.0 specification. You can find out more details about specification at [doc](https://swagger.io/specification/v3/). Some useful links: - [GraphScope Repository](https://github.com/alibaba/GraphScope) - [The Source API definition for GraphScope Interactive](https://github.com/GraphScope/portal/tree/main/httpservice)
7
+
8
+ The version of the OpenAPI document: 1.0.0
9
+ Contact: graphscope@alibaba-inc.com
10
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
11
+
12
+ Do not edit the class manually.
13
+ """ # noqa: E501
14
+
15
+ from typing import Any, Optional
16
+ from typing_extensions import Self
17
+
18
+ class OpenApiException(Exception):
19
+ """The base exception class for all OpenAPIExceptions"""
20
+
21
+
22
+ class ApiTypeError(OpenApiException, TypeError):
23
+ def __init__(self, msg, path_to_item=None, valid_classes=None,
24
+ key_type=None) -> None:
25
+ """ Raises an exception for TypeErrors
26
+
27
+ Args:
28
+ msg (str): the exception message
29
+
30
+ Keyword Args:
31
+ path_to_item (list): a list of keys an indices to get to the
32
+ current_item
33
+ None if unset
34
+ valid_classes (tuple): the primitive classes that current item
35
+ should be an instance of
36
+ None if unset
37
+ key_type (bool): False if our value is a value in a dict
38
+ True if it is a key in a dict
39
+ False if our item is an item in a list
40
+ None if unset
41
+ """
42
+ self.path_to_item = path_to_item
43
+ self.valid_classes = valid_classes
44
+ self.key_type = key_type
45
+ full_msg = msg
46
+ if path_to_item:
47
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
48
+ super(ApiTypeError, self).__init__(full_msg)
49
+
50
+
51
+ class ApiValueError(OpenApiException, ValueError):
52
+ def __init__(self, msg, path_to_item=None) -> None:
53
+ """
54
+ Args:
55
+ msg (str): the exception message
56
+
57
+ Keyword Args:
58
+ path_to_item (list) the path to the exception in the
59
+ received_data dict. None if unset
60
+ """
61
+
62
+ self.path_to_item = path_to_item
63
+ full_msg = msg
64
+ if path_to_item:
65
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
66
+ super(ApiValueError, self).__init__(full_msg)
67
+
68
+
69
+ class ApiAttributeError(OpenApiException, AttributeError):
70
+ def __init__(self, msg, path_to_item=None) -> None:
71
+ """
72
+ Raised when an attribute reference or assignment fails.
73
+
74
+ Args:
75
+ msg (str): the exception message
76
+
77
+ Keyword Args:
78
+ path_to_item (None/list) the path to the exception in the
79
+ received_data dict
80
+ """
81
+ self.path_to_item = path_to_item
82
+ full_msg = msg
83
+ if path_to_item:
84
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
85
+ super(ApiAttributeError, self).__init__(full_msg)
86
+
87
+
88
+ class ApiKeyError(OpenApiException, KeyError):
89
+ def __init__(self, msg, path_to_item=None) -> None:
90
+ """
91
+ Args:
92
+ msg (str): the exception message
93
+
94
+ Keyword Args:
95
+ path_to_item (None/list) the path to the exception in the
96
+ received_data dict
97
+ """
98
+ self.path_to_item = path_to_item
99
+ full_msg = msg
100
+ if path_to_item:
101
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
102
+ super(ApiKeyError, self).__init__(full_msg)
103
+
104
+
105
+ class ApiException(OpenApiException):
106
+
107
+ def __init__(
108
+ self,
109
+ status=None,
110
+ reason=None,
111
+ http_resp=None,
112
+ *,
113
+ body: Optional[str] = None,
114
+ data: Optional[Any] = None,
115
+ ) -> None:
116
+ self.status = status
117
+ self.reason = reason
118
+ self.body = body
119
+ self.data = data
120
+ self.headers = None
121
+
122
+ if http_resp:
123
+ if self.status is None:
124
+ self.status = http_resp.status
125
+ if self.reason is None:
126
+ self.reason = http_resp.reason
127
+ if self.body is None:
128
+ try:
129
+ self.body = http_resp.data.decode('utf-8')
130
+ except Exception:
131
+ pass
132
+ self.headers = http_resp.getheaders()
133
+
134
+ @classmethod
135
+ def from_response(
136
+ cls,
137
+ *,
138
+ http_resp,
139
+ body: Optional[str],
140
+ data: Optional[Any],
141
+ ) -> Self:
142
+ if http_resp.status == 400:
143
+ raise BadRequestException(http_resp=http_resp, body=body, data=data)
144
+
145
+ if http_resp.status == 401:
146
+ raise UnauthorizedException(http_resp=http_resp, body=body, data=data)
147
+
148
+ if http_resp.status == 403:
149
+ raise ForbiddenException(http_resp=http_resp, body=body, data=data)
150
+
151
+ if http_resp.status == 404:
152
+ raise NotFoundException(http_resp=http_resp, body=body, data=data)
153
+
154
+ if 500 <= http_resp.status <= 599:
155
+ raise ServiceException(http_resp=http_resp, body=body, data=data)
156
+ raise ApiException(http_resp=http_resp, body=body, data=data)
157
+
158
+ def __str__(self):
159
+ """Custom error messages for exception"""
160
+ error_message = "({0})\n"\
161
+ "Reason: {1}\n".format(self.status, self.reason)
162
+ if self.headers:
163
+ error_message += "HTTP response headers: {0}\n".format(
164
+ self.headers)
165
+
166
+ if self.data or self.body:
167
+ error_message += "HTTP response body: {0}\n".format(self.data or self.body)
168
+
169
+ return error_message
170
+
171
+
172
+ class BadRequestException(ApiException):
173
+ pass
174
+
175
+
176
+ class NotFoundException(ApiException):
177
+ pass
178
+
179
+
180
+ class UnauthorizedException(ApiException):
181
+ pass
182
+
183
+
184
+ class ForbiddenException(ApiException):
185
+ pass
186
+
187
+
188
+ class ServiceException(ApiException):
189
+ pass
190
+
191
+
192
+ def render_path(path_to_item):
193
+ """Returns a string representation of a path"""
194
+ result = ""
195
+ for pth in path_to_item:
196
+ if isinstance(pth, int):
197
+ result += "[{0}]".format(pth)
198
+ else:
199
+ result += "['{0}']".format(pth)
200
+ return result