1

API を 1000 回要求する (ネットワーク要求を送信して応答を処理する) 場合、最初に 1000 個の要求をすべて送信した後に応答の処理を開始し、次に応答を処理します。

asyncio が完了したら、await 位置コードを返すように指示できますか?

import asyncio

import httpx

# request_time = 10
request_time = 1000 # large enough to ensure previous responses return

limits = httpx.Limits(max_connections=5)
client = httpx.AsyncClient(limits=limits)


async def request_baidu(i):
    # async with httpx.AsyncClient(limits=limits) as client:
        print(f"===> %d" % i)
        r = await client.get("http://www.baidu.com")
        # print(r.status_code)
        print(f"<=== %d" % i) # How to ensure return to run this code, not make a new request (run a new task `request_baidu` here)


async def main():
    request_list = [asyncio.create_task(request_baidu(i)) for i in range(request_time)]
    await asyncio.gather(*request_list)

if __name__ == '__main__':
    asyncio.run(main())

結果

# request_time = 10

===> 0
===> 1
===> 2
===> 3
===> 4
===> 5
===> 6
===> 7
===> 8
===> 9
<=== 3 # (we can see it continue to handle response after sending all request)
<=== 4
<=== 0 
<=== 1
<=== 2
<=== 5
<=== 6
<=== 7
<=== 8
<=== 9

期待される結果:</h3>
===> 0
===> 1
<=== 0 #(continue handle response when there is some response)
===> 2
===> 3
<=== 1
<=== 2
===> 4
# ...

4

1 に答える 1