gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:09:50 24 4
gpt4 key购买 nike

我的问题是关于在 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()
我不明白,为什么这里的上下文管理器。我发现的只是 __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()
我挖了 aiohttp.ClientSession及其上下文管理器来源,但我没有发现任何可以澄清情况的内容。
最后,我的问题是:有什么区别?

最佳答案

通过 async with 显式管理响应, 不是必要的,但建议。 async with的目的用于响应对象是为了安全及时地释放响应使用的资源(通过调用 resp.release() )。也就是说,即使发生错误,资源也会被释放并可用于进一步的请求/响应。
否则,aiohttp也会释放响应资源,但不保证及时性。最坏的情况是这会延迟任意时间,即直到应用程序结束和外部资源(例如套接字)超时。

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

关于python - 在 aiohttp 中执行请求时 await 和 async-with 之间有本质区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65380093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com