-
Notifications
You must be signed in to change notification settings - Fork 38
/
rest.py
346 lines (295 loc) · 13.9 KB
/
rest.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
import json
import logging
import re
import ssl
from urllib.parse import urlencode
import zlib
import urllib3 # type: ignore
from datadog_api_client.exceptions import (
ApiException,
UnauthorizedException,
ForbiddenException,
NotFoundException,
ServiceException,
ApiValueError,
)
logger = logging.getLogger(__name__)
RETRY_AFTER_STATUS_CODES = frozenset([429, 500, 501, 502, 503, 504, 505, 506, 507, 509, 510, 511])
RETRY_ALLOWED_METHODS = frozenset(["GET", "PUT", "DELETE", "POST", "PATCH"])
class ClientRetry(urllib3.util.Retry):
RETRY_AFTER_STATUS_CODES = RETRY_AFTER_STATUS_CODES
DEFAULT_ALLOWED_METHODS = RETRY_ALLOWED_METHODS
def get_retry_after(self, response):
"""
This method overrides the default "Retry-after" header and uses dd's X-Ratelimit-Reset header
and gets the value of X-Ratelimit-Reset in seconds.
"""
retry_after = response.headers.get("X-Ratelimit-Reset")
if retry_after is None:
return None
return self.parse_retry_after(retry_after)
def is_retry(self, method, status_code, has_retry_after=False):
if method not in self.DEFAULT_ALLOWED_METHODS:
return False
if self.status_forcelist and status_code in self.status_forcelist:
return True
return self.total and self.respect_retry_after_header and (status_code in self.RETRY_AFTER_STATUS_CODES)
class RESTClientObject:
def __init__(self, configuration, pools_size=4, maxsize=4):
# urllib3.PoolManager will pass all kw parameters to connectionpool
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680
# maxsize is the number of requests to host that are allowed in parallel
# Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html
# cert_reqs
if configuration.verify_ssl:
cert_reqs = ssl.CERT_REQUIRED
else:
cert_reqs = ssl.CERT_NONE
addition_pool_args = {}
if configuration.assert_hostname is not None:
addition_pool_args["assert_hostname"] = configuration.assert_hostname
if configuration.enable_retry:
retries = ClientRetry(
total=configuration.max_retries,
backoff_factor=configuration.retry_backoff_factor,
)
addition_pool_args["retries"] = retries
if configuration.socket_options is not None:
addition_pool_args["socket_options"] = configuration.socket_options
# https pool manager
if configuration.proxy:
self.pool_manager = urllib3.ProxyManager(
num_pools=pools_size,
maxsize=maxsize,
cert_reqs=cert_reqs,
ca_certs=configuration.ssl_ca_cert,
cert_file=configuration.cert_file,
key_file=configuration.key_file,
proxy_url=configuration.proxy,
proxy_headers=configuration.proxy_headers,
**addition_pool_args,
)
else:
self.pool_manager = urllib3.PoolManager(
num_pools=pools_size,
maxsize=maxsize,
cert_reqs=cert_reqs,
ca_certs=configuration.ssl_ca_cert,
cert_file=configuration.cert_file,
key_file=configuration.key_file,
**addition_pool_args,
)
def request(
self,
method,
url,
query_params=None,
headers=None,
body=None,
post_params=None,
preload_content=True,
request_timeout=None,
):
"""Perform requests.
:param method: http request method
:param url: http request url
:param query_params: query parameters in the 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 preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
: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 post_params and body:
raise ApiValueError("body parameter cannot be used with post_params parameter.")
post_params = post_params or {}
headers = headers or {}
timeout = None
if request_timeout:
if isinstance(request_timeout, (int, float)):
timeout = urllib3.Timeout(total=request_timeout)
elif isinstance(request_timeout, tuple) and len(request_timeout) == 2:
timeout = urllib3.Timeout(connect=request_timeout[0], read=request_timeout[1])
try:
request_kwargs = {}
# For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
if method in ("POST", "PUT", "PATCH", "OPTIONS", "DELETE"):
# Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests
if method != "DELETE" and "Content-Type" not in headers and body is not None:
headers["Content-Type"] = "application/json"
if query_params:
url += "?" + urlencode(query_params)
if "Content-Type" not in headers or re.search("json", headers["Content-Type"], re.IGNORECASE):
request_body = None
if body is not None:
request_body = json.dumps(body)
if headers.get("Content-Encoding") == "gzip":
compressor = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
request_body = compressor.compress(request_body.encode("utf-8")) + compressor.flush()
elif headers.get("Content-Encoding") == "deflate":
request_body = zlib.compress(request_body.encode("utf-8"))
elif headers.get("Content-Encoding") == "zstd1":
import zstandard as zstd
compressor = zstd.ZstdCompressor()
request_body = compressor.compress(request_body.encode("utf-8"))
request_kwargs["body"] = request_body
elif headers["Content-Type"] == "application/x-www-form-urlencoded":
request_kwargs["encode_multipart"] = False
request_kwargs["fields"] = post_params
elif headers["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"]
request_kwargs["encode_multipart"] = True
request_kwargs["fields"] = post_params
# 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, bytes)):
request_kwargs["body"] = body
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:
request_kwargs["fields"] = query_params
r = self.pool_manager.request(
method, url, preload_content=preload_content, timeout=timeout, headers=headers, **request_kwargs
)
except urllib3.exceptions.SSLError as e:
msg = "{0}\n{1}".format(type(e).__name__, str(e))
raise ApiException(status=0, reason=msg)
if preload_content:
# log response body
logger.debug("response body: %s", r.data)
if not 200 <= r.status <= 299:
if r.status == 401:
raise UnauthorizedException(http_resp=r)
if r.status == 403:
raise ForbiddenException(http_resp=r)
if r.status == 404:
raise NotFoundException(http_resp=r)
if 500 <= r.status <= 599:
raise ServiceException(http_resp=r)
raise ApiException(http_resp=r)
return r
class _AioSonicResponseWrapper:
def __init__(self, response, data):
self.response = response
self.status = response.status_code
self.reason = response.response_initial.get("reason")
self.data = data
self.headers = response.headers.copy()
class AsyncRESTClientObject:
def __init__(self, configuration):
import aiosonic # type: ignore
proxy = None
if configuration.proxy:
proxy = aiosonic.Proxy(configuration.proxy, configuration.proxy_headers)
self._client = aiosonic.HTTPClient(proxy=proxy, verify_ssl=configuration.verify_ssl)
self._configuration = configuration
def _retry(self, method, response, counter):
if (
not self._configuration.enable_retry
or counter >= self._configuration.max_retries
or method not in RETRY_ALLOWED_METHODS
or response.status_code not in RETRY_AFTER_STATUS_CODES
):
return 0
retry_after = response.headers.get("X-Ratelimit-Reset")
if retry_after is None:
return self._configuration.retry_backoff_factor * (2 ** (counter))
return int(retry_after)
async def request(
self,
method,
url,
query_params=None,
headers=None,
body=None,
post_params=None,
preload_content=True,
request_timeout=None,
):
"""Perform requests.
:param method: http request method
:param url: http request url
:param query_params: query parameters in the 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 preload_content: if False, the raw HTTP response object will
be returned without reading/decoding response
data. Default is True.
: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.
"""
assert not post_params, "not supported for now"
if request_timeout is not None:
from aiosonic.timeout import Timeouts # type: ignore
if isinstance(request_timeout, (int, float)):
request_timeout = Timeouts(request_timeout=request_timeout)
else:
request_timeout = Timeouts(sock_connect=request_timeout[0], sock_read=request_timeout[1])
request_body = None
if (
"Content-Type" not in headers
or re.search("json", headers["Content-Type"], re.IGNORECASE)
and body is not None
):
request_body = json.dumps(body)
if headers.get("Content-Encoding") == "gzip":
compress = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
request_body = compress.compress(request_body.encode("utf-8")) + compress.flush()
elif headers.get("Content-Encoding") == "deflate":
request_body = zlib.compress(request_body.encode("utf-8"))
elif headers.get("Content-Encoding") == "zstd1":
import zstandard as zstd
compressor = zstd.ZstdCompressor()
request_body = compressor.compress(request_body.encode("utf-8"))
counter = 0
while True:
response = await self._client.request(
url, method, headers, query_params, request_body, timeouts=request_timeout
)
retry = self._retry(method, response, counter)
if not retry:
break
import asyncio
await asyncio.sleep(retry)
counter += 1
if not 200 <= response.status_code <= 299:
data = b""
if preload_content:
data = await response.content()
r = _AioSonicResponseWrapper(response, data)
if response.status_code == 401:
raise UnauthorizedException(http_resp=r)
if response.status_code == 403:
raise ForbiddenException(http_resp=r)
if response.status_code == 404:
raise NotFoundException(http_resp=r)
if 500 <= response.status_code <= 599:
raise ServiceException(http_resp=r)
raise ApiException(http_resp=r)
return response