-
Notifications
You must be signed in to change notification settings - Fork 0
/
aiorequests.py
99 lines (66 loc) · 2.74 KB
/
aiorequests.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import asyncio
from functools import partial
from typing import Optional, Any
import requests
from requests import *
async def run_sync_func(func, *args, **kwargs) -> Any:
return await asyncio.get_event_loop().run_in_executor(
None, partial(func, *args, **kwargs))
class AsyncResponse:
def __init__(self, response: requests.Response):
self.raw_response = response
@property
def ok(self) -> bool:
return self.raw_response.ok
@property
def status_code(self) -> int:
return self.raw_response.status_code
@property
def headers(self):
return self.raw_response.headers
@property
def url(self):
return self.raw_response.url
@property
def encoding(self):
return self.raw_response.encoding
@property
def cookies(self):
return self.raw_response.cookies
def __repr__(self):
return '<AsyncResponse [%s]>' % self.raw_response.status_code
def __bool__(self):
return self.ok
@property
async def content(self) -> Optional[bytes]:
return await run_sync_func(lambda: self.raw_response.content)
@property
async def text(self) -> str:
return await run_sync_func(lambda: self.raw_response.text)
async def json(self, **kwargs) -> Any:
return await run_sync_func(self.raw_response.json, **kwargs)
def raise_for_status(self):
self.raw_response.raise_for_status()
async def request(method, url, **kwargs) -> AsyncResponse:
return AsyncResponse(await run_sync_func(requests.request,
method=method, url=url, **kwargs))
async def get(url, params=None, **kwargs) -> AsyncResponse:
return AsyncResponse(
await run_sync_func(requests.get, url=url, params=params, **kwargs))
async def options(url, **kwargs) -> AsyncResponse:
return AsyncResponse(
await run_sync_func(requests.options, url=url, **kwargs))
async def head(url, **kwargs) -> AsyncResponse:
return AsyncResponse(await run_sync_func(requests.head, url=url, **kwargs))
async def post(url, data=None, json=None, **kwargs) -> AsyncResponse:
return AsyncResponse(await run_sync_func(requests.post, url=url,
data=data, json=json, **kwargs))
async def put(url, data=None, **kwargs) -> AsyncResponse:
return AsyncResponse(
await run_sync_func(requests.put, url=url, data=data, **kwargs))
async def patch(url, data=None, **kwargs) -> AsyncResponse:
return AsyncResponse(
await run_sync_func(requests.patch, url=url, data=data, **kwargs))
async def delete(url, **kwargs) -> AsyncResponse:
return AsyncResponse(
await run_sync_func(requests.delete, url=url, **kwargs))