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
提示清除相关问题 更多 >
编程相关推荐