簡體   English   中英

Asyncio 沒有並行運行 Aiohttp 請求

[英]Asyncio not running Aiohttp requests in parallel

我想使用 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+抽象出事件循環的創建,您也可以考慮使用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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM