Repository navigation
Expand file tree
/
Copy pathhttp_client.py
More file actions
42 lines (38 loc) · 1.59 KB
/
Copy pathhttp_client.py
File metadata and controls
42 lines (38 loc) · 1.59 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
import time
import logging
from typing import Any, Dict
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
logger = logging.getLogger(__name__)
class HttpClient:
def __init__(self, timeout_s: int, manual_retries: int, backoff_base: int):
self.timeout_s = timeout_s
self.manual_retries = manual_retries
self.backoff_base = backoff_base
self.session = self._build_session()
def _build_session(self) -> requests.Session:
s = requests.Session()
retries = Retry(
total=3,
backoff_factor=0.5,
status_forcelist=(429, 500, 502, 503, 504),
allowed_methods=frozenset({"GET", "POST"}),
raise_on_status=False,
)
adapter = HTTPAdapter(max_retries=retries, pool_connections=10, pool_maxsize=10)
s.mount("http://", adapter)
s.mount("https://", adapter)
s.headers.update({"Content-Type": "application/json"})
return s
def post_json_with_retry(self, url: str, payload: Dict[str, Any]) -> requests.Response:
err = None
for attempt in range(1, self.manual_retries + 1):
try:
return self.session.post(url, json=payload, timeout=self.timeout_s)
except requests.RequestException as e:
err = e
logger.warning("POST attempt %d/%d failed: %s", attempt, self.manual_retries, e)
if attempt < self.manual_retries:
time.sleep(self.backoff_base ** attempt)
raise RuntimeError(f"All retries failed: {err}")