When working with the popular Python asynchronous HTTP client/server framework aiohttp, it's important to properly close your ClientSession and connections to avoid issues like resource leaks or failing to send pending data.
Use async with for ClientSessions
The recommended way to create an
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
# use session
This automatically handles closing the session for you even if exceptions occur.
Without
session = aiohttp.ClientSession()
try:
# make requests
finally:
await session.close()
Forgetting to close sessions can lead to TCP connection leaks over time.
Close ClientResponses
Similarly, use
async with session.get(url) as response:
# response handling
This sends any pending data and frees the connection.
Lingering Tasks May Prevent Closing
One catch when closing aiohttp connections is that if you still have coroutine tasks executing that rely on the session/connection, the close will wait for those to finish.
So make sure you
await fetch_data(session) # wait for tasks using session
await session.close()
This prevents errors from trying to access a closed connection in background tasks.
Key Takeaways
Following these tips will help prevent issues when wrapping up aiohttp clients!