[英]asyncio tasks using aiohttp.ClientSession
我正在使用python 3.7并尝试制作可以异步进入多个域的搜寻器。 我正在为此asyncio和aiohttp使用,但是我遇到了aiohttp.ClientSession的问题。 这是我的简化代码:
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
print(await response.text())
async def main():
loop = asyncio.get_event_loop()
async with aiohttp.ClientSession(loop=loop) as session:
cwlist = [loop.create_task(fetch(session, url)) for url in ['http://python.org', 'http://google.com']]
asyncio.gather(*cwlist)
if __name__ == "__main__":
asyncio.run(main())
抛出的异常是这样的:
_GatheringFuture异常以后再也不会检索到:<_GatheringFuture完成的异常= RuntimeError('会话已关闭')>
我在这里做错了什么?
您忘记await
asyncio.gather
结果:
async with aiohttp.ClientSession(loop=loop) as session:
cwlist = [loop.create_task(fetch(session, url)) for url in ['http://python.org', 'http://google.com']]
await asyncio.gather(*cwlist)
如果您曾经有一个不包含await
表达式的async with
那么您应该相当可疑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.