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