为什么 aiohttp 弃用了 ClientSession 中的 loop 参数?
Why aiohttp deprecated the loop parameter in ClientSession?
在 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
那么为什么不推荐使用该参数以及如何正确使用会话?
这个问题已经解决in this issue which is advising that the client session object be created within a coroutine to avoid errors that are difficult to debug. The preferred usage is 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())
在 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
那么为什么不推荐使用该参数以及如何正确使用会话?
这个问题已经解决in this issue which is advising that the client session object be created within a coroutine to avoid errors that are difficult to debug. The preferred usage is 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())