Python Asyncio未并行运行Aiohttp请求

Python Asyncio未并行运行Aiohttp请求,python,python-asyncio,aiohttp,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 respon

我想使用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())
我希望它并行执行所有请求,但它们是一个接一个地执行的。
虽然我后来使用线程解决了这个问题,但我想知道这有什么问题?

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

您也可以考虑使用Python版本<代码> 3.7 +<代码>,抽象出事件循环的创建:

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())

您可以使用列表理解任务=[asyncio.create_task(getResponse(session,i))为范围(10)内的i简化循环)感谢您的反馈,列表理解肯定是首选。明白!非常感谢你!除非您特别需要与每个
getResponse
关联的
任务
,否则可以省略
create\u任务
[getResponse(session,i)for i in range(10)]
Wow,感谢@dirn的评论,我没有意识到这一点。我已经用建议更新了答案。相关