4

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 1

3

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()
Sign up to request clarification or add additional context in comments.

3 Comments

You need to catch both asyncio.CancelledError and aiohttp.ClientDisconnectedError
Oh I didn't know about that one; I'll update my answer. Thanks!
Where would I use this? I am pretty much at a loss.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.