gpt4 book ai didi

python - 为什么 aiohttp 弃用了 ClientSession 中的 loop 参数?

转载 作者:太空狗 更新时间:2023-10-29 21:11:45 29 4
gpt4 key购买 nike

在aiohttp的doc阅读:

  • loop – event loop used for processing HTTP requests. If loop is None the constructor borrows it from connector if specified. asyncio.get_event_loop() is used for getting default event loop otherwise.

Deprecated since version 2.0.

我用谷歌搜索但没有得到关于为什么不推荐使用 loop 参数的任何说明。

我经常像这样创建 ClientSession 对象:

loop = asyncio.get_event_loop()
session = aiohttp.ClientSession(loop=loop)

现在 loop 参数被破坏了,但是只要调用 aiohttp.ClientSession() 没有循环就会得到警告:

Creating a client session outside of coroutine

那么为什么不推荐使用该参数以及如何正确使用 session ?

最佳答案

这个问题已解决 in this issue建议在协程中创建客户端 session 对象以避免难以调试的错误。首选用法是 demonstrated here ;供引用:

async def fetch(client):
async with client.get('http://python.org') as resp:
assert resp.status == 200
return await resp.text()

async def main():
async with aiohttp.ClientSession() as client:
html = await fetch(client)
print(html)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

关于python - 为什么 aiohttp 弃用了 ClientSession 中的 loop 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48125023/

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