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