36 lines
1.1 KiB
Python
36 lines
1.1 KiB
Python
import requests
|
|
|
|
|
|
class HttpClient:
|
|
def __init__(self, endpoint, token):
|
|
self._endpoint = endpoint.rstrip("/")
|
|
self._session = requests.Session()
|
|
self._session.headers.update({
|
|
"Authorization": f"Bearer {token}",
|
|
"User-Agent": "Mozilla/5.0",
|
|
})
|
|
|
|
def get(self, path, **kwargs):
|
|
kwargs.setdefault("timeout", 10)
|
|
r = self._session.get(f"{self._endpoint}{path}", **kwargs)
|
|
r.raise_for_status()
|
|
return r.json()
|
|
|
|
def post(self, path, data=None, **kwargs):
|
|
kwargs.setdefault("timeout", 30)
|
|
url = f"{self._endpoint}{path}"
|
|
r = self._session.post(url, json=(data if data is not None else {}), **kwargs)
|
|
if not r.ok:
|
|
raise Exception(f"POST {path}: {r.status_code} {r.reason}: {r.text[:200]}")
|
|
result = {}
|
|
try:
|
|
parsed = r.json()
|
|
if isinstance(parsed, dict):
|
|
result = parsed
|
|
except Exception:
|
|
pass
|
|
loc = r.headers.get("Location", "")
|
|
if loc:
|
|
result["_location"] = loc
|
|
return result
|