-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrest.py
More file actions
159 lines (135 loc) · 7.44 KB
/
rest.py
File metadata and controls
159 lines (135 loc) · 7.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# coding: utf-8
"""
STACKIT Resource Manager API
API v2 to manage resource containers - organizations, folders, projects incl. labels ### Resource Management STACKIT resource management handles the terms _Organization_, _Folder_, _Project_, _Label_, and the hierarchical structure between them. Technically, organizations, folders, and projects are _Resource Containers_ to which a _Label_ can be attached to. The STACKIT _Resource Manager_ provides CRUD endpoints to query and to modify the state. ### Organizations STACKIT organizations are the base element to create and to use cloud-resources. An organization is bound to one customer account. Organizations have a lifecycle. - Organizations are always the root node in resource hierarchy and do not have a parent ### Projects STACKIT projects are needed to use cloud-resources. Projects serve as wrapper for underlying technical structures and processes. Projects have a lifecycle. Projects compared to folders may have different policies. - Projects are optional, but mandatory for cloud-resource usage - A project can be created having either an organization, or a folder as parent - A project must not have a project as parent - Project names under the same parent must not be unique - Root organization cannot be changed ### Label STACKIT labels are key-value pairs including a resource container reference. Labels can be defined and attached freely to resource containers by which resources can be organized and queried. - Policy-based, immutable labels may exists
The version of the OpenAPI document: 2.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import io
import json
import re
import requests
from stackit.core.authorization import Authorization
from stackit.core.configuration import Configuration
from stackit.resourcemanager.exceptions import ApiException, ApiValueError
RESTResponseType = requests.Response
class RESTResponse(io.IOBase):
def __init__(self, resp) -> None:
self.response = resp
self.status = resp.status_code
self.reason = resp.reason
self.data = None
def read(self):
if self.data is None:
self.data = self.response.content
return self.data
def getheaders(self):
"""Returns a dictionary of the response headers."""
return self.response.headers
def getheader(self, name, default=None):
"""Returns a given response header."""
return self.response.headers.get(name, default)
class RESTClientObject:
def __init__(self, config: Configuration) -> None:
self.session = config.custom_http_session if config.custom_http_session else requests.Session()
authorization = Authorization(config)
self.session.auth = authorization.auth_method
def request(self, method, url, headers=None, body=None, post_params=None, _request_timeout=None):
"""Perform requests.
:param method: http request method
:param url: http request url
:param headers: http request headers
:param body: request json body, for `application/json`
:param post_params: request post parameters,
`application/x-www-form-urlencoded`
and `multipart/form-data`
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
"""
method = method.upper()
if method not in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"]:
raise ValueError("Method %s not allowed", method)
if post_params and body:
raise ApiValueError("body parameter cannot be used with post_params parameter.")
post_params = post_params or {}
headers = headers or {}
try:
# For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]:
# no content type provided or payload is json
content_type = headers.get("Content-Type")
if not content_type or re.search("json", content_type, re.IGNORECASE):
request_body = None
if body is not None:
request_body = json.dumps(body)
r = self.session.request(
method,
url,
data=request_body,
headers=headers,
timeout=_request_timeout,
)
elif content_type == "application/x-www-form-urlencoded":
r = self.session.request(
method,
url,
params=post_params,
headers=headers,
timeout=_request_timeout,
)
elif content_type == "multipart/form-data":
# must del headers['Content-Type'], or the correct
# Content-Type which generated by urllib3 will be
# overwritten.
del headers["Content-Type"]
# Ensures that dict objects are serialized
post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a, b) for a, b in post_params]
r = self.session.request(
method,
url,
files=post_params,
headers=headers,
timeout=_request_timeout,
)
# Pass a `string` parameter directly in the body to support
# other content types than JSON when `body` argument is
# provided in serialized form.
elif isinstance(body, str) or isinstance(body, bytes):
r = self.session.request(
method,
url,
data=body,
headers=headers,
timeout=_request_timeout,
)
elif headers["Content-Type"].startswith("text/") and isinstance(body, bool):
request_body = "true" if body else "false"
r = self.session.request(
method,
url,
data=request_body,
headers=headers,
timeout=_request_timeout,
)
else:
# Cannot generate the request from given parameters
msg = """Cannot prepare a request message for provided
arguments. Please check that your arguments match
declared content type."""
raise ApiException(status=0, reason=msg)
# For `GET`, `HEAD`
else:
r = self.session.request(
method,
url,
params={},
headers=headers,
timeout=_request_timeout,
)
except requests.exceptions.SSLError as e:
msg = "\n".join([type(e).__name__, str(e)])
raise ApiException(status=0, reason=msg)
return RESTResponse(r)