I think the problem here is that you've already used the ClientSession
object in an async context manager. When the async with aiohttp.ClientSession() as session:
block exits, it tears down the session's connection pool.
Advice from others to use a single ClientSession()
object per request goes directly against what the documentation says. To take advantage of the connection pooling, the session should be kept for a long time. The documentation is very unclear on how to do this though.
One way is with the asyncio_loop_local
package (see here). With this package, you can do this:
_ClientSession = asyncio_loop_local.sticky_singleton_acm(aiohttp.ClientSession)
async with _ClientSession() as session:
... do your request ...
async with _ClientSession() as session:
... and another request ...
This will transparently re-use ClientSession()
objects, with one per event loop and with the context managers managed cleanly for you.
__aexit__()
of ClientSessionContextManager will be called. – Terrain_SessionRequestContextManager
notClientSessionContextManager
– Terrain