在 aiohttp 中执行请求时 await 和 async-with 之间有本质区别吗?

Fed*_*kin 6 python asynchronous async-await python-asyncio aiohttp

我的问题是关于做出回应的正确方式 aiohttp

官方 aiohttp 文档为我们提供了进行异步查询的示例:

session = aiohttp.ClientSession()

async with session.get('http://httpbin.org/get') as resp:
    print(resp.status)
    print(await resp.text())

await session.close()
Run Code Online (Sandbox Code Playgroud)

我不明白,为什么这里的上下文管理器。我发现的只是__aexit__()方法等待resp.release()方法。但是文档还告诉我们resp.release()一般不需要等待。

这一切真的让我很困惑。

如果我发现下面的代码更具可读性并且不是那么嵌套,为什么要这样做?

session = aiohttp.ClientSession()

resp = await session.get('http://httpbin.org/get')
print(resp.status)
print(await resp.text())

# I finally have not get the essence of this method.
# I've tried both using and not using this method in my code,
# I've not found any difference in behaviour.
# await resp.release()

await session.close()
Run Code Online (Sandbox Code Playgroud)

我已经深入研究了aiohttp.ClientSession它的上下文管理器来源,但我没有发现任何可以澄清情况的东西。

最后,我的问题是:有什么区别?

Mis*_*agi 2

通过 , 显式管理响应async with不是必要的,但建议这样做。for 响应对象的目的async with安全、及时地释放响应所使用的资源(通过调用resp.release())。也就是说,即使发生错误,资源也会被释放并可用于进一步的请求/响应。

否则,也会aiohttp释放响应资源,但不保证及时性。最坏的情况是,这会延迟任意时间,即直到应用程序结束和外部资源(例如套接字)超时。


aiohttp如果没有发生错误(在这种情况下清理未使用的资源)和/或如果应用程序很短(在这种情况下有足够的资源不需要重复使用),则差异并不明显。但是,由于错误可能会意外发生并且aiohttp是针对许多请求/响应而设计的,因此建议始终默认通过 提示清理async with