Skip to content

Instantly share code, notes, and snippets.

@mrzechonek
Last active May 21, 2020 15:00
Show Gist options
  • Save mrzechonek/a968b4fee2b985526601062c9265f6c2 to your computer and use it in GitHub Desktop.
Save mrzechonek/a968b4fee2b985526601062c9265f6c2 to your computer and use it in GitHub Desktop.
import inspect
import asyncio
from async_generator import asynccontextmanager
class Response:
def __init__(self, body):
self._body = body
async def body(self):
return self._body
class Request:
def __init__(self, url, **kwargs):
self.url = url
self.kwargs= kwargs
async def __aenter__(self):
print(f"Request {self.url} with {self.kwargs}")
return Response(f"Response to {self.url}")
async def __aexit__(self, *args, **kwargs):
pass
@asynccontextmanager
async def request(url, kwargs):
if inspect.isawaitable(kwargs):
kwargs = await kwargs
kwargs.setdefault('headers', {}).update(dict(UserAgent='test'))
async with Request(url, **kwargs) as rsp:
yield rsp
def authorized_request(url):
async def get_kwargs():
return dict(headers=dict(Auth='foobar'))
return request(url, kwargs=get_kwargs())
async def get_simple():
async with authorized_request("/simple") as rsp:
return await rsp.body()
def get_full():
return authorized_request("/schedule")
async def main():
print(await get_simple())
async with get_full() as rsp:
print(await rsp.body())
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment