【问题标题】:asyncio tasks using aiohttp.ClientSession使用 aiohttp.ClientSession 的异步任务
【发布时间】:2019-08-05 03:26:03
【问题描述】:

我正在使用 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 finished exception="RuntimeError('Session" is closed>

我在这里做错了什么?

【问题讨论】:

    标签: python aiohttp python-asyncio


    【解决方案1】:

    你忘了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,你应该相当怀疑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-24
      • 2017-10-30
      • 2015-10-28
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多