-
-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathhttp.py
50 lines (37 loc) · 1.41 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
import aiohttp
import json
from aiohttp.client_exceptions import ContentTypeError
class HTTPResponse:
def __init__(
self, status: int, response: str,
res_method: str, headers: dict[str, str]
):
self.status = status
self.response = response
self.res_method = res_method
self.headers = headers
def __repr__(self) -> str:
return f"<HTTPResponse status={self.status} res_method='{self.res_method}'>"
async def query(url, method="get", res_method="text", *args, **kwargs) -> HTTPResponse:
""" Make a HTTP request using aiohttp """
session = aiohttp.ClientSession()
async with getattr(session, method.lower())(url, *args, **kwargs) as res:
try:
r = await getattr(res, res_method)()
except ContentTypeError:
if res_method == "json":
r = json.loads(await res.text())
output = HTTPResponse(
status=res.status,
response=r,
res_method=res_method,
headers=res.headers
)
await session.close()
return output
async def get(url, *args, **kwargs) -> HTTPResponse:
""" Shortcut for query(url, "get", *args, **kwargs) """
return await query(url, "get", *args, **kwargs)
async def post(url, *args, **kwargs) -> HTTPResponse:
""" Shortcut for query(url, "post", *args, **kwargs) """
return await query(url, "post", *args, **kwargs)