forked from scaleway/scaleway-sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
192 lines (141 loc) · 4.6 KB
/
api.py
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import json
import logging
from dataclasses import dataclass
from typing import IO, Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union
import requests
from requests import Response
from .client import Client
Body = Union[
str, bytes, Mapping[str, Any], Iterable[Tuple[str, Optional[str]]], IO[Any]
]
Params = Mapping[str, Any]
@dataclass
class APILogger:
logger: logging.Logger
identifier: int
def log_request(
self,
method: str,
url: str,
params: List[Tuple[str, Any]],
headers: Dict[str, str],
body: Optional[str],
) -> None:
if not self.logger.isEnabledFor(logging.DEBUG):
return
raw_params = "&".join([f"{k}={v}" for (k, v) in params])
debug_headers = {
**headers,
"x-auth-token": "*****",
}
title = (
f"--------------- Scaleway SDK REQUEST {self.identifier} ---------------\n"
)
log = f"{title}\n"
log += f"{method} {url}?{raw_params}\n"
for k, v in debug_headers.items():
log += f"{k}: {v}\n"
if body is not None:
log += "\n"
log += body
log += "\n"
log += "-" * len(title)
self.logger.debug(log)
def log_response(
self,
response: requests.Response,
) -> None:
if not self.logger.isEnabledFor(logging.DEBUG):
return
title = (
f"--------------- Scaleway SDK RESPONSE {self.identifier} ---------------"
)
ok = "OK" if response.ok else "NOK"
log = f"{title}\n"
log += f"HTTP {response.status_code} {ok}\n"
for k, v in response.headers.items():
log += f"{k}: {v}\n"
if response.text:
log += f"\n{response.text}\n"
log += "-" * len(title)
self.logger.debug(log)
@dataclass
class ScalewayException(Exception):
response: Response
@property
def status_code(self) -> int:
return self.response.status_code
def __str__(self) -> str:
return self.response.text
@dataclass
class ValidationError(ScalewayException):
errors: Dict[str, str]
class API:
def __init__(self, client: Client, *, bypass_validation: bool = False):
if not bypass_validation:
client.validate()
self.client = client
self._log = logging.getLogger("scaleway")
def _request(
self,
method: str,
path: str,
params: Params = {},
headers: Dict[str, str] = {},
body: Optional[Body] = None,
) -> requests.Response:
additional_headers: Dict[str, str] = {}
method = method.upper()
if method == "POST" or method == "PUT" or method == "PATCH":
additional_headers["Content-Type"] = "application/json; charset=utf-8"
if body is None:
body = {}
raw_body = json.dumps(body) if body is not None else None
request_params: List[Tuple[str, Any]] = []
for k, v in params.items():
if v is None:
continue
if isinstance(v, list):
for item in v:
request_params.append((k, item))
else:
request_params.append((k, v))
headers = {
"accept": "application/json",
"x-auth-token": self.client.secret_key or "",
"user-agent": self.client.user_agent,
**additional_headers,
**headers,
}
url = f"{self.client.api_url}{path}"
logger = APILogger(self._log, self.client._increment_request_count())
logger.log_request(
method=method,
url=url,
params=request_params,
headers=headers,
body=raw_body,
)
response = requests.request(
method=method,
url=url,
params=request_params,
headers=headers,
data=raw_body,
verify=not self.client.api_allow_insecure,
)
logger.log_response(
response=response,
)
return response
def _throw_on_error(self, res: requests.Response) -> None:
if res.status_code >= 400:
data = res.json()
if data:
if "message" in data:
message = data["message"]
if message == "Validation Error":
raise ValidationError(res, data["fields"])
raise ScalewayException(res)
raise ScalewayException(res)
raise ScalewayException(res)