Async HTTP sessions use context managers for connection pooling.
1import asyncio2import aiohttp34# Single session for multiple requests5async def fetch_all(urls):6 async with aiohttp.ClientSession() as session:7 tasks = [fetch_one(session, url) for url in urls]8 return await asyncio.gather(*tasks)910async def fetch_one(session, url):11 async with session.get(url) as response:12 return await response.json()1314# Custom async context manager15from contextlib import asynccontextmanager1617@asynccontextmanager18async def api_client(base_url):19 async with aiohttp.ClientSession(base_url=base_url) as session:20 yield ApiWrapper(session)2122class ApiWrapper:23 def __init__(self, session):24 self.session = session2526 async def get(self, path):27 async with self.session.get(path) as resp:28 return await resp.json()2930# Usage31async def main():32 async with api_client("https://api.example.com") as api:33 data = await api.get("/users")34 print(data)3536asyncio.run(main())
Benefits: