I have a long running request during which I push data down to a client as it is received. However, the request requires some resources that are created server side that I'd like to clean up whenever the client disconnects. I've looked through the docs, but I can't seem to find a way to detect when that happens. Any ideas?
1 Answer
This isn't super obvious looking at the docs, but the key here is that the asyncio server will throw a CancelledError
into handler coroutine when the connection is closed. You can catch the CancelledError
wherever you wait for an asynchronous operation to complete.
Using this, I clean up after a connection with something like this:
async def passthrough_data_until_disconnect():
await create_resources()
while True:
try:
await get_next_data_item()
except (concurrent.futures.CancelledError,
aiohttp.ClientDisconnectedError):
# The request has been cancelled, due to a disconnect
await do_cleanup()
# Re-raise the cancellation error so the handler
# task gets cancelled for real
raise
else:
await write_data_to_client_response()
-
4You need to catch both
asyncio.CancelledError
andaiohttp.ClientDisconnectedError
Mar 29, 2016 at 10:16 -
Oh I didn't know about that one; I'll update my answer. Thanks! Mar 29, 2016 at 20:19
-