Asyncio 未并行运行 Aiohttp 请求

Ans*_*waj 5 python python-asyncio aiohttp

我想使用 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())
Run Code Online (Sandbox Code Playgroud)

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

Kri*_*sia 16

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

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

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())
Run Code Online (Sandbox Code Playgroud)