在取消未来之前正确关闭asyncio.ClientSession

时间:2017-11-21 07:27:56

标签: python-3.x python-asyncio

我有一份我正在等待的任务列表,最快的响应将被保存,其余的将被取消

done, pending = await asyncio.wait(
    futures, return_when=FIRST_COMPLETED)

print(done.pop().result())

for future in pending:
    future.cancel()

这些期货中的每一个都有这个

session = asyncio.CreateSession()
# some code to request
# some code to process response
await session.close()

当我取消其他期货时,我收到警告

Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x10f95c6d8>

在取消任务之前关闭此开放会话的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

1)

for future in pending:
    future.cancel()

如果您想取消某些内容,您不仅应该调用cancel()方法,还要等待实际取消的任务:

from contextlib import suppress

for task in pending:
    task.cancel()
    with suppress(asyncio.CancelledError):
        await task

read this answer了解取消的效果。

2)

session = asyncio.CreateSession()
# some code to request
# some code to process response
await session.close()

在这些行之间的某处CancelledError(或其他例外)可以引发。如果它发生,将永远不会到达行await session.close()

在Python中的任何地方,如果你需要一些资源并且需要在以后释放它,你应该总是将所有代码包装在/释放尝试/最终阻止之间:

session = asyncio.CreateSession()
try:
    # some code to request
    # some code to process response
finally:
    await session.close()

同样,这是与asyncio相关的常见模式not only