-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.py
59 lines (47 loc) · 1.67 KB
/
http.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
from typing import Optional, Union
import httpx
from yarl import URL
BASE_URL = "https://some-random-api.ml"
class API_ERROR(Exception):
def __init__(self, message, http_code):
self.http_code = http_code
self.message = message
super().__init__(self.message)
class GET:
def __init__(
self, endpoint: Union[tuple[str, ...], str], queries: Optional[dict] = None
):
self.endpoint = endpoint
self.queries = queries if queries else dict()
self.queries = {k: str(v) for k, v in self.queries.items() if v is not None}
self.base_url = URL(BASE_URL)
def __enter__(self):
resp = httpx.get(self.parse_url())
return self.response(resp)
async def __aenter__(self):
async with httpx.AsyncClient() as client:
resp = await client.get(self.parse_url())
return self.response(resp)
def parse_url(self):
if isinstance(self.endpoint, tuple):
url = self.base_url
for path in self.endpoint:
url /= path
else:
url = self.base_url / self.endpoint
url = url.with_query(self.queries)
return url.human_repr()
def response(self, resp):
content_type = resp.headers.get("content-type").split(";")[0].strip()
if content_type == "application/json":
error = resp.json().get("error")
if error is not None:
raise API_ERROR(error, resp.status_code)
else:
return resp
else:
return resp
def __exit__(self, exc_type, exc, tb):
pass
async def __aexit__(self, exc_type, exc, tb):
pass