【问题标题】:Asyncio not running Aiohttp requests in parallelAsyncio 没有并行运行 Aiohttp 请求
【发布时间】:2021-06-17 12:42:41
【问题描述】:

我想使用 python 并行运行许多 HTTP 请求。 我用 asyncio 尝试了这个名为 aiohttp 的模块。

import aiohttp
import asyncio

async def main():
    async with aiohttp.ClientSession() as session:
        for i in range(10):
            async with session.get('https://httpbin.org/get') as response:
                html = await response.text()
                print('done' + str(i))

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

我希望它并行执行所有请求,但它们是一个接一个执行的。 虽然,后来我用线程解决了这个问题,但我想知道这有什么问题?

【问题讨论】:

标签: python python-asyncio aiohttp


【解决方案1】:

您需要以并发方式发出请求。目前,您有一个由main() 定义的任务,因此http 请求以串行方式为该任务运行。

如果您使用的是抽象出事件循环创建的 Python 版本 3.7+,您也可以考虑使用 asyncio.run()

import aiohttp
import asyncio

async def getResponse(session, i):
    async with session.get('https://httpbin.org/get') as response:
        html = await response.text()
        print('done' + str(i))

async def main():
    async with aiohttp.ClientSession() as session:
        tasks = [getResponse(session, i) for i in range(10)] # create list of tasks
        await asyncio.gather(*tasks) # execute them in concurrent manner

asyncio.run(main())

【讨论】:

  • 你可以用列表理解来简化循环tasks = [asyncio.create_task(getResponse(session, i)) for i in range(10)]
  • 感谢您的反馈,列表理解绝对应该是首选。
  • 明白!非常感谢!
  • 除非您特别需要与每个getResponse 关联的Task,否则您可以省略create_task[getResponse(session, i) for i in range(10)]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 2016-12-14
相关资源
最近更新 更多