15
15
import requests
16
16
from tenacity import (
17
17
retry ,
18
+ retry_if_exception ,
18
19
stop_after_attempt ,
19
20
wait_exponential ,
20
- retry_if_exception_type ,
21
21
)
22
22
from .utilities import parse_validation_response
23
23
26
26
RETRY_MIN = 4
27
27
RETRY_MAX = 10
28
28
RETRY_STOP = 5
29
+ RETRY_STATUS_CODES = (
30
+ http .HTTPStatus .BAD_REQUEST ,
31
+ http .HTTPStatus .SERVICE_UNAVAILABLE ,
32
+ http .HTTPStatus .GATEWAY_TIMEOUT ,
33
+ http .HTTPStatus .REQUEST_TIMEOUT ,
34
+ http .HTTPStatus .TOO_EARLY ,
35
+ )
36
+ RETRY_EXCEPTION_TYPES = (RuntimeError , requests .exceptions .ConnectionError )
29
37
30
38
31
39
def set_json_header (headers : dict [str , str ]) -> dict [str , str ]:
@@ -38,10 +46,18 @@ def set_json_header(headers: dict[str, str]) -> dict[str, str]:
38
46
return headers
39
47
40
48
49
+ def is_retryable_exception (exception : Exception ) -> bool :
50
+ """Returns if the given exception should lead to a retry being called"""
51
+ if isinstance (exception , requests .HTTPError ):
52
+ return exception .status_code in RETRY_STATUS_CODES
53
+
54
+ return isinstance (exception , RETRY_EXCEPTION_TYPES )
55
+
56
+
41
57
@retry (
42
58
wait = wait_exponential (multiplier = RETRY_MULTIPLIER , min = RETRY_MIN , max = RETRY_MAX ),
43
59
stop = stop_after_attempt (RETRY_STOP ),
44
- retry = retry_if_exception_type ( RuntimeError ),
60
+ retry = retry_if_exception ( is_retryable_exception ),
45
61
reraise = True ,
46
62
)
47
63
def post (
@@ -104,7 +120,7 @@ def post(
104
120
105
121
@retry (
106
122
wait = wait_exponential (multiplier = RETRY_MULTIPLIER , min = RETRY_MIN , max = RETRY_MAX ),
107
- retry = retry_if_exception_type ( RuntimeError ),
123
+ retry = retry_if_exception ( is_retryable_exception ),
108
124
stop = stop_after_attempt (RETRY_STOP ),
109
125
reraise = True ,
110
126
)
@@ -127,7 +143,7 @@ def put(
127
143
data to put
128
144
is_json : bool, optional
129
145
send as JSON string, by default True
130
- timeout : _type_ , optional
146
+ timeout : int , optional
131
147
timeout of request, by default DEFAULT_API_TIMEOUT
132
148
133
149
Returns
@@ -148,6 +164,12 @@ def put(
148
164
return response
149
165
150
166
167
+ @retry (
168
+ wait = wait_exponential (multiplier = RETRY_MULTIPLIER , min = RETRY_MIN , max = RETRY_MAX ),
169
+ retry = retry_if_exception (is_retryable_exception ),
170
+ stop = stop_after_attempt (RETRY_STOP ),
171
+ reraise = True ,
172
+ )
151
173
def get (
152
174
url : str , headers : dict [str , str ], timeout : int = DEFAULT_API_TIMEOUT
153
175
) -> requests .Response :
@@ -159,7 +181,7 @@ def get(
159
181
URL to put to
160
182
headers : dict[str, str]
161
183
headers for the post request
162
- timeout : _type_ , optional
184
+ timeout : int , optional
163
185
timeout of request, by default DEFAULT_API_TIMEOUT
164
186
165
187
Returns
0 commit comments