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