import asyncio
from contextlib import asynccontextmanager
import aiohttp
@asynccontextmanager
async def http_session(timeout: int = 10):
session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout))
try:
yield session
finally:
await session.close()
async def main():
async with http_session(timeout=5) as session:
async with session.get("https://api.github.com") as r:
print(r.status)
# session is guaranteed-closed here, even on exception
asyncio.run(main())
Create a free account and build your private vault. Share publicly whenever you want.