4

我有一个长时间运行的请求,在此期间我将收到的数据推送到客户端。但是,该请求需要一些在服务器端创建的资源,我想在客户端断开连接时清理这些资源。我查看了文档,但似乎找不到一种方法来检测何时发生这种情况。有任何想法吗?

4

1 回答 1

3

这在查看文档时并不是很明显,但这里的关键是CancelledError当连接关闭时,异步服务器将向处理程序协程中抛出一个。CancelledError您可以在等待异步操作完成的任何地方捕获。

使用它,我在与以下内容建立连接后进行清理:

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()
于 2016-03-29T07:03:35.740 回答