stackit-telemetrylink 0.1.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 (24) hide show
  1. src/stackit/telemetrylink/__init__.py +81 -0
  2. src/stackit/telemetrylink/api/__init__.py +4 -0
  3. src/stackit/telemetrylink/api/default_api.py +3296 -0
  4. src/stackit/telemetrylink/api_client.py +650 -0
  5. src/stackit/telemetrylink/api_response.py +23 -0
  6. src/stackit/telemetrylink/configuration.py +163 -0
  7. src/stackit/telemetrylink/exceptions.py +217 -0
  8. src/stackit/telemetrylink/models/__init__.py +36 -0
  9. src/stackit/telemetrylink/models/create_or_update_folder_telemetry_link_payload.py +126 -0
  10. src/stackit/telemetrylink/models/create_or_update_organization_telemetry_link_payload.py +126 -0
  11. src/stackit/telemetrylink/models/create_or_update_project_telemetry_link_payload.py +126 -0
  12. src/stackit/telemetrylink/models/partial_update_folder_telemetry_link_payload.py +138 -0
  13. src/stackit/telemetrylink/models/partial_update_organization_telemetry_link_payload.py +138 -0
  14. src/stackit/telemetrylink/models/partial_update_project_telemetry_link_payload.py +138 -0
  15. src/stackit/telemetrylink/models/response4xx.py +82 -0
  16. src/stackit/telemetrylink/models/telemetry_link_request.py +138 -0
  17. src/stackit/telemetrylink/models/telemetry_link_response.py +158 -0
  18. src/stackit/telemetrylink/py.typed +0 -0
  19. src/stackit/telemetrylink/rest.py +164 -0
  20. stackit_telemetrylink-0.1.0.dist-info/METADATA +48 -0
  21. stackit_telemetrylink-0.1.0.dist-info/RECORD +24 -0
  22. stackit_telemetrylink-0.1.0.dist-info/WHEEL +4 -0
  23. stackit_telemetrylink-0.1.0.dist-info/licenses/LICENSE.md +201 -0
  24. stackit_telemetrylink-0.1.0.dist-info/licenses/NOTICE.txt +2 -0
@@ -0,0 +1,650 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ STACKIT Telemetry Link API
5
+
6
+ This API provides endpoints for managing Telemetry Links. The Telemetry Link enables Log Routing towards a defined Telemetry Router.
7
+
8
+ The version of the OpenAPI document: 1beta.0.0
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+ import datetime
15
+ import decimal
16
+ import json
17
+ import mimetypes
18
+ import os
19
+ import re
20
+ import tempfile
21
+ import uuid
22
+ from enum import Enum
23
+ from typing import Dict, List, Optional, Tuple, Union
24
+ from urllib.parse import quote
25
+
26
+ from dateutil.parser import parse
27
+ from pydantic import SecretStr
28
+ from stackit.core.configuration import Configuration
29
+
30
+ import stackit.telemetrylink.models
31
+ from stackit.telemetrylink import rest
32
+ from stackit.telemetrylink.api_response import ApiResponse
33
+ from stackit.telemetrylink.api_response import T as ApiResponseT
34
+ from stackit.telemetrylink.configuration import HostConfiguration
35
+ from stackit.telemetrylink.exceptions import (
36
+ ApiException,
37
+ )
38
+
39
+
40
+ RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]]
41
+
42
+
43
+ class ApiClient:
44
+ """Generic API client for OpenAPI client library builds.
45
+
46
+ OpenAPI generic API client. This client handles the client-
47
+ server communication, and is invariant across implementations. Specifics of
48
+ the methods and models for each application are generated from the OpenAPI
49
+ templates.
50
+
51
+ :param configuration: .Configuration object for this client
52
+ :param header_name: a header to pass when making calls to the API.
53
+ :param header_value: a header value to pass when making calls to
54
+ the API.
55
+ :param cookie: a cookie to include in the header when making calls
56
+ to the API
57
+ """
58
+
59
+ PRIMITIVE_TYPES = (float, bool, bytes, str, int)
60
+ NATIVE_TYPES_MAPPING = {
61
+ "int": int,
62
+ "long": int, # TODO remove as only py3 is supported?
63
+ "float": float,
64
+ "str": str,
65
+ "bool": bool,
66
+ "date": datetime.date,
67
+ "datetime": datetime.datetime,
68
+ "decimal": decimal.Decimal,
69
+ "UUID": uuid.UUID,
70
+ "object": object,
71
+ }
72
+ _pool = None
73
+
74
+ def __init__(self, configuration, header_name=None, header_value=None, cookie=None) -> None:
75
+ self.config: Configuration = configuration
76
+
77
+ if self.config.custom_endpoint is None:
78
+ host_config = HostConfiguration(region=self.config.region, server_index=self.config.server_index)
79
+ self.host = host_config.host
80
+ else:
81
+ self.host = self.config.custom_endpoint
82
+
83
+ self.rest_client = rest.RESTClientObject(self.config)
84
+ self.default_headers = {}
85
+ if header_name is not None:
86
+ self.default_headers[header_name] = header_value
87
+ self.cookie = cookie
88
+ # Set default User-Agent.
89
+ self.user_agent = "stackit-sdk-python/telemetrylink"
90
+
91
+ def __enter__(self):
92
+ return self
93
+
94
+ def __exit__(self, exc_type, exc_value, traceback):
95
+ pass
96
+
97
+ @property
98
+ def user_agent(self):
99
+ """User agent for this API client"""
100
+ return self.default_headers["User-Agent"]
101
+
102
+ @user_agent.setter
103
+ def user_agent(self, value):
104
+ self.default_headers["User-Agent"] = value
105
+
106
+ def set_default_header(self, header_name, header_value):
107
+ self.default_headers[header_name] = header_value
108
+
109
+ _default = None
110
+
111
+ @classmethod
112
+ def get_default(cls):
113
+ """Return new instance of ApiClient.
114
+
115
+ This method returns newly created, based on default constructor,
116
+ object of ApiClient class or returns a copy of default
117
+ ApiClient.
118
+
119
+ :return: The ApiClient object.
120
+ """
121
+ if cls._default is None:
122
+ cls._default = ApiClient()
123
+ return cls._default
124
+
125
+ @classmethod
126
+ def set_default(cls, default):
127
+ """Set default instance of ApiClient.
128
+
129
+ It stores default ApiClient.
130
+
131
+ :param default: object of ApiClient.
132
+ """
133
+ cls._default = default
134
+
135
+ def param_serialize(
136
+ self,
137
+ method,
138
+ resource_path,
139
+ path_params=None,
140
+ query_params=None,
141
+ header_params=None,
142
+ body=None,
143
+ post_params=None,
144
+ files=None,
145
+ auth_settings=None,
146
+ collection_formats=None,
147
+ _host=None,
148
+ _request_auth=None,
149
+ ) -> RequestSerialized:
150
+ """Builds the HTTP request params needed by the request.
151
+ :param method: Method to call.
152
+ :param resource_path: Path to method endpoint.
153
+ :param path_params: Path parameters in the url.
154
+ :param query_params: Query parameters in the url.
155
+ :param header_params: Header parameters to be
156
+ placed in the request header.
157
+ :param body: Request body.
158
+ :param post_params dict: Request post form parameters,
159
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
160
+ :param auth_settings list: Auth Settings names for the request.
161
+ :param files dict: key -> filename, value -> filepath,
162
+ for `multipart/form-data`.
163
+ :param collection_formats: dict of collection formats for path, query,
164
+ header, and post parameters.
165
+ :param _request_auth: set to override the auth_settings for an a single
166
+ request; this effectively ignores the authentication
167
+ in the spec for a single request.
168
+ :return: tuple of form (path, http_method, query_params, header_params,
169
+ body, post_params, files)
170
+ """
171
+
172
+ # header parameters
173
+ header_params = header_params or {}
174
+ header_params.update(self.default_headers)
175
+ if self.cookie:
176
+ header_params["Cookie"] = self.cookie
177
+ if header_params:
178
+ header_params = self.sanitize_for_serialization(header_params)
179
+ header_params = dict(self.parameters_to_tuples(header_params, collection_formats))
180
+
181
+ # path parameters
182
+ if path_params:
183
+ path_params = self.sanitize_for_serialization(path_params)
184
+ path_params = self.parameters_to_tuples(path_params, collection_formats)
185
+ for k, v in path_params:
186
+ # specified safe chars, encode everything
187
+ resource_path = resource_path.replace("{%s}" % k, quote(str(v)))
188
+
189
+ # post parameters
190
+ if post_params or files:
191
+ post_params = post_params if post_params else []
192
+ post_params = self.sanitize_for_serialization(post_params)
193
+ post_params = self.parameters_to_tuples(post_params, collection_formats)
194
+ if files:
195
+ post_params.extend(self.files_parameters(files))
196
+
197
+ # body
198
+ if body:
199
+ body = self.sanitize_for_serialization(body)
200
+
201
+ # request url
202
+ if _host is None:
203
+ url = self.host + resource_path
204
+ else:
205
+ # use server/host defined in path or operation instead
206
+ url = _host + resource_path
207
+
208
+ # query parameters
209
+ if query_params:
210
+ query_params = self.sanitize_for_serialization(query_params)
211
+ url_query = self.parameters_to_url_query(query_params, collection_formats)
212
+ url += "?" + url_query
213
+
214
+ return method, url, header_params, body, post_params
215
+
216
+ def call_api(
217
+ self, method, url, header_params=None, body=None, post_params=None, _request_timeout=None
218
+ ) -> rest.RESTResponse:
219
+ """Makes the HTTP request (synchronous)
220
+ :param method: Method to call.
221
+ :param url: Path to method endpoint.
222
+ :param header_params: Header parameters to be
223
+ placed in the request header.
224
+ :param body: Request body.
225
+ :param post_params dict: Request post form parameters,
226
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
227
+ :param _request_timeout: timeout setting for this request.
228
+ :return: RESTResponse
229
+ """
230
+
231
+ try:
232
+ # perform request and return response
233
+ response_data = self.rest_client.request(
234
+ method,
235
+ url,
236
+ headers=header_params,
237
+ body=body,
238
+ post_params=post_params,
239
+ _request_timeout=_request_timeout,
240
+ )
241
+
242
+ except ApiException as e:
243
+ raise e
244
+
245
+ return response_data
246
+
247
+ def response_deserialize(
248
+ self, response_data: rest.RESTResponse, response_types_map: Optional[Dict[str, ApiResponseT]] = None
249
+ ) -> ApiResponse[ApiResponseT]:
250
+ """Deserializes response into an object.
251
+ :param response_data: RESTResponse object to be deserialized.
252
+ :param response_types_map: dict of response types.
253
+ :return: ApiResponse
254
+ """
255
+
256
+ msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
257
+ if response_data.data is None:
258
+ raise ValueError(msg)
259
+
260
+ response_type = response_types_map.get(str(response_data.status), None)
261
+ if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
262
+ # if not found, look for '1XX', '2XX', etc.
263
+ response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
264
+
265
+ # deserialize response data
266
+ response_text = None
267
+ return_data = None
268
+ try:
269
+ if response_type in ("bytearray", "bytes"):
270
+ return_data = response_data.data
271
+ elif response_type == "file":
272
+ return_data = self.__deserialize_file(response_data)
273
+ elif response_type is not None:
274
+ match = None
275
+ content_type = response_data.headers.get("content-type")
276
+ if content_type is not None:
277
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
278
+ encoding = match.group(1) if match else "utf-8"
279
+ response_text = response_data.data.decode(encoding)
280
+ return_data = self.deserialize(response_text, response_type, content_type)
281
+ finally:
282
+ if not 200 <= response_data.status <= 299:
283
+ raise ApiException.from_response(
284
+ http_resp=response_data,
285
+ body=response_text,
286
+ data=return_data,
287
+ )
288
+
289
+ return ApiResponse(
290
+ status_code=response_data.status,
291
+ data=return_data,
292
+ headers=response_data.headers,
293
+ raw_data=response_data.data,
294
+ )
295
+
296
+ def sanitize_for_serialization(self, obj):
297
+ """Builds a JSON POST object.
298
+
299
+ If obj is None, return None.
300
+ If obj is SecretStr, return obj.get_secret_value()
301
+ If obj is str, int, long, float, bool, return directly.
302
+ If obj is datetime.datetime, datetime.date
303
+ convert to string in iso8601 format.
304
+ If obj is decimal.Decimal return string representation.
305
+ If obj is list, sanitize each element in the list.
306
+ If obj is dict, return the dict.
307
+ If obj is OpenAPI model, return the properties dict.
308
+
309
+ :param obj: The data to serialize.
310
+ :return: The serialized form of data.
311
+ """
312
+ if obj is None:
313
+ return None
314
+ elif isinstance(obj, Enum):
315
+ return obj.value
316
+ elif isinstance(obj, SecretStr):
317
+ return obj.get_secret_value()
318
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
319
+ return obj
320
+ elif isinstance(obj, uuid.UUID):
321
+ return str(obj)
322
+ elif isinstance(obj, list):
323
+ return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj]
324
+ elif isinstance(obj, tuple):
325
+ return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj)
326
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
327
+ return obj.isoformat()
328
+ elif isinstance(obj, decimal.Decimal):
329
+ return str(obj)
330
+ elif isinstance(obj, dict):
331
+ return {key: self.sanitize_for_serialization(val) for key, val in obj.items()}
332
+
333
+ # Convert model obj to dict except
334
+ # attributes `openapi_types`, `attribute_map`
335
+ # and attributes which value is not None.
336
+ # Convert attribute name to json key in
337
+ # model definition for request.
338
+ if hasattr(obj, "to_dict") and callable(getattr(obj, "to_dict")): # noqa: B009
339
+ obj_dict = obj.to_dict()
340
+ else:
341
+ obj_dict = obj.__dict__
342
+
343
+ return self.sanitize_for_serialization(obj_dict)
344
+
345
+ def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]):
346
+ """Deserializes response into an object.
347
+
348
+ :param response: RESTResponse object to be deserialized.
349
+ :param response_type: class literal for
350
+ deserialized object, or string of class name.
351
+ :param content_type: content type of response.
352
+
353
+ :return: deserialized object.
354
+ """
355
+
356
+ # fetch data from response object
357
+ if content_type is None:
358
+ try:
359
+ data = json.loads(response_text)
360
+ except ValueError:
361
+ data = response_text
362
+ elif re.match(r"^application/(json|[\w!#$&.+\-^_]+\+json)\s*(;|$)", content_type, re.IGNORECASE):
363
+ if response_text == "":
364
+ data = ""
365
+ else:
366
+ data = json.loads(response_text)
367
+ elif re.match(r"^text\/[a-z.+-]+\s*(;|$)", content_type, re.IGNORECASE):
368
+ data = response_text
369
+ else:
370
+ raise ApiException(status=0, reason="Unsupported content type: {0}".format(content_type))
371
+
372
+ return self.__deserialize(data, response_type)
373
+
374
+ def __deserialize(self, data, klass):
375
+ """Deserializes dict, list, str into an object.
376
+
377
+ :param data: dict, list or str.
378
+ :param klass: class literal, or string of class name.
379
+
380
+ :return: object.
381
+ """
382
+ if data is None:
383
+ return None
384
+
385
+ if isinstance(klass, str):
386
+ if klass.startswith("List["):
387
+ m = re.match(r"List\[(.*)]", klass)
388
+ if m is None:
389
+ raise ValueError("Malformed List type definition")
390
+ sub_kls = m.group(1)
391
+ return [self.__deserialize(sub_data, sub_kls) for sub_data in data]
392
+
393
+ if klass.startswith("Dict["):
394
+ m = re.match(r"Dict\[([^,]*), (.*)]", klass)
395
+ if m is None:
396
+ raise ValueError("Malformed Dict type definition")
397
+ sub_kls = m.group(2)
398
+ return {k: self.__deserialize(v, sub_kls) for k, v in data.items()}
399
+
400
+ # convert str to class
401
+ if klass in self.NATIVE_TYPES_MAPPING:
402
+ klass = self.NATIVE_TYPES_MAPPING[klass]
403
+ else:
404
+ klass = getattr(stackit.telemetrylink.models, klass)
405
+
406
+ if klass in self.PRIMITIVE_TYPES:
407
+ return self.__deserialize_primitive(data, klass)
408
+ elif klass is object:
409
+ return self.__deserialize_object(data)
410
+ elif klass is datetime.date:
411
+ return self.__deserialize_date(data)
412
+ elif klass is datetime.datetime:
413
+ return self.__deserialize_datetime(data)
414
+ elif klass is decimal.Decimal:
415
+ return decimal.Decimal(data)
416
+ elif klass is uuid.UUID:
417
+ return uuid.UUID(data)
418
+ elif issubclass(klass, Enum):
419
+ return self.__deserialize_enum(data, klass)
420
+ else:
421
+ return self.__deserialize_model(data, klass)
422
+
423
+ def parameters_to_tuples(self, params, collection_formats):
424
+ """Get parameters as list of tuples, formatting collections.
425
+
426
+ :param params: Parameters as dict or list of two-tuples
427
+ :param dict collection_formats: Parameter collection formats
428
+ :return: Parameters as list of tuples, collections formatted
429
+ """
430
+ new_params: List[Tuple[str, str]] = []
431
+ if collection_formats is None:
432
+ collection_formats = {}
433
+ for k, v in params.items() if isinstance(params, dict) else params:
434
+ if k in collection_formats:
435
+ collection_format = collection_formats[k]
436
+ if collection_format == "multi":
437
+ new_params.extend((k, value) for value in v)
438
+ else:
439
+ if collection_format == "ssv":
440
+ delimiter = " "
441
+ elif collection_format == "tsv":
442
+ delimiter = "\t"
443
+ elif collection_format == "pipes":
444
+ delimiter = "|"
445
+ else: # csv is the default
446
+ delimiter = ","
447
+ new_params.append((k, delimiter.join(str(value) for value in v)))
448
+ else:
449
+ new_params.append((k, v))
450
+ return new_params
451
+
452
+ def parameters_to_url_query(self, params, collection_formats):
453
+ """Get parameters as list of tuples, formatting collections.
454
+
455
+ :param params: Parameters as dict or list of two-tuples
456
+ :param dict collection_formats: Parameter collection formats
457
+ :return: URL query string (e.g. a=Hello%20World&b=123)
458
+ """
459
+ new_params: List[Tuple[str, str]] = []
460
+ if collection_formats is None:
461
+ collection_formats = {}
462
+ for k, v in params.items() if isinstance(params, dict) else params:
463
+ if isinstance(v, bool):
464
+ v = str(v).lower()
465
+ if isinstance(v, (int, float)):
466
+ v = str(v)
467
+ if isinstance(v, dict):
468
+ v = json.dumps(v)
469
+
470
+ if k in collection_formats:
471
+ collection_format = collection_formats[k]
472
+ if collection_format == "multi":
473
+ new_params.extend((k, quote(str(value))) for value in v)
474
+ else:
475
+ if collection_format == "ssv":
476
+ delimiter = " "
477
+ elif collection_format == "tsv":
478
+ delimiter = "\t"
479
+ elif collection_format == "pipes":
480
+ delimiter = "|"
481
+ else: # csv is the default
482
+ delimiter = ","
483
+ new_params.append((k, delimiter.join(quote(str(value)) for value in v)))
484
+ else:
485
+ new_params.append((k, quote(str(v))))
486
+
487
+ return "&".join(["=".join(map(str, item)) for item in new_params])
488
+
489
+ def files_parameters(
490
+ self,
491
+ files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]],
492
+ ):
493
+ """Builds form parameters.
494
+
495
+ :param files: File parameters.
496
+ :return: Form parameters with files.
497
+ """
498
+ params = []
499
+ for k, v in files.items():
500
+ if isinstance(v, str):
501
+ with open(v, "rb") as f:
502
+ filename = os.path.basename(f.name)
503
+ filedata = f.read()
504
+ elif isinstance(v, bytes):
505
+ filename = k
506
+ filedata = v
507
+ elif isinstance(v, tuple):
508
+ filename, filedata = v
509
+ elif isinstance(v, list):
510
+ for file_param in v:
511
+ params.extend(self.files_parameters({k: file_param}))
512
+ continue
513
+ else:
514
+ raise ValueError("Unsupported file value")
515
+ mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
516
+ params.append(tuple([k, tuple([filename, filedata, mimetype])]))
517
+ return params
518
+
519
+ def select_header_accept(self, accepts: List[str]) -> Optional[str]:
520
+ """Returns `Accept` based on an array of accepts provided.
521
+
522
+ :param accepts: List of headers.
523
+ :return: Accept (e.g. application/json).
524
+ """
525
+ if not accepts:
526
+ return None
527
+
528
+ for accept in accepts:
529
+ if re.search("json", accept, re.IGNORECASE):
530
+ return accept
531
+
532
+ return accepts[0]
533
+
534
+ def select_header_content_type(self, content_types):
535
+ """Returns `Content-Type` based on an array of content_types provided.
536
+
537
+ :param content_types: List of content-types.
538
+ :return: Content-Type (e.g. application/json).
539
+ """
540
+ if not content_types:
541
+ return None
542
+
543
+ for content_type in content_types:
544
+ if re.search("json", content_type, re.IGNORECASE):
545
+ return content_type
546
+
547
+ return content_types[0]
548
+
549
+ def __deserialize_file(self, response):
550
+ """Deserializes body to file
551
+
552
+ Saves response body into a file in a temporary folder,
553
+ using the filename from the `Content-Disposition` header if provided.
554
+
555
+ handle file downloading
556
+ save response body into a tmp file and return the instance
557
+
558
+ :param response: RESTResponse.
559
+ :return: file path.
560
+ """
561
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
562
+ os.close(fd)
563
+ os.remove(path)
564
+
565
+ content_disposition = response.headers.get("Content-Disposition")
566
+ if content_disposition:
567
+ m = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition)
568
+ if m is None:
569
+ raise ValueError("Unexpected 'content-disposition' header value")
570
+ filename = os.path.basename(m.group(1)) # Strip any directory traversal
571
+ if filename in ("", ".", ".."): # fall back to tmp filename
572
+ filename = os.path.basename(path)
573
+ path = os.path.join(os.path.dirname(path), filename)
574
+
575
+ with open(path, "wb") as f:
576
+ f.write(response.data)
577
+
578
+ return path
579
+
580
+ def __deserialize_primitive(self, data, klass):
581
+ """Deserializes string to primitive type.
582
+
583
+ :param data: str.
584
+ :param klass: class literal.
585
+
586
+ :return: int, long, float, str, bool.
587
+ """
588
+ try:
589
+ return klass(data)
590
+ except UnicodeEncodeError:
591
+ return str(data)
592
+ except TypeError:
593
+ return data
594
+
595
+ def __deserialize_object(self, value):
596
+ """Return an original value.
597
+
598
+ :return: object.
599
+ """
600
+ return value
601
+
602
+ def __deserialize_date(self, string):
603
+ """Deserializes string to date.
604
+
605
+ :param string: str.
606
+ :return: date.
607
+ """
608
+ try:
609
+ return parse(string).date()
610
+ except ImportError:
611
+ return string
612
+ except ValueError:
613
+ raise rest.ApiException(status=0, reason="Failed to parse `{0}` as date object".format(string))
614
+
615
+ def __deserialize_datetime(self, string):
616
+ """Deserializes string to datetime.
617
+
618
+ The string should be in iso8601 datetime format.
619
+
620
+ :param string: str.
621
+ :return: datetime.
622
+ """
623
+ try:
624
+ return parse(string)
625
+ except ImportError:
626
+ return string
627
+ except ValueError:
628
+ raise rest.ApiException(status=0, reason=("Failed to parse `{0}` as datetime object".format(string)))
629
+
630
+ def __deserialize_enum(self, data, klass):
631
+ """Deserializes primitive type to enum.
632
+
633
+ :param data: primitive type.
634
+ :param klass: class literal.
635
+ :return: enum value.
636
+ """
637
+ try:
638
+ return klass(data)
639
+ except ValueError:
640
+ raise rest.ApiException(status=0, reason=("Failed to parse `{0}` as `{1}`".format(data, klass)))
641
+
642
+ def __deserialize_model(self, data, klass):
643
+ """Deserializes list or dict to model.
644
+
645
+ :param data: dict, list.
646
+ :param klass: class literal.
647
+ :return: model object.
648
+ """
649
+
650
+ return klass.from_dict(data)
@@ -0,0 +1,23 @@
1
+ """API response object."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Generic, Mapping, Optional, TypeVar
6
+
7
+ from pydantic import BaseModel, Field, StrictBytes, StrictInt
8
+
9
+
10
+ T = TypeVar("T")
11
+
12
+
13
+ class ApiResponse(BaseModel, Generic[T]):
14
+ """
15
+ API response object
16
+ """
17
+
18
+ status_code: StrictInt = Field(description="HTTP status code")
19
+ headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers")
20
+ data: T = Field(description="Deserialized data given the data type")
21
+ raw_data: StrictBytes = Field(description="Raw data (HTTP response body)")
22
+
23
+ model_config = {"arbitrary_types_allowed": True}