httpxで非同期リクエストの例:考え中のお客様がGoogle検索
https://speakerdeck.com/jrfk/django-3-dot-2-asgidui-ying-kowakunai-asyncio-ji-chu-toasync-viewfalseshi-isuo?slide=178
code:search_async.py
import asyncio
from time import time
import httpx
async def long_think(client, num):
print(f"ちょっと待ってね ({num})")
response = await client.get("https://www.google.com/search?q=おいしいお蕎麦は?")
return num, response, "ざるそば"
async def order():
print("ご注文は?")
async with httpx.AsyncClient() as client:
tasks = [
long_think(client, 1),
long_think(client, 2),
long_think(client, 3),
]
result = await asyncio.gather(*tasks)
print(result)
start = time()
asyncio.run(order(), debug=True)
print("time: ", time() - start)
code:実行結果
$ python search_async.py
ご注文は?
ちょっと待ってね (1)
ちょっと待ってね (2)
ちょっと待ってね (3)
[(1, <Response 200 OK>, 'ざるそば'), (2, <Response 200 OK>, 'ざるそば'), (3, <Response 200 OK>, 'ざるそば')]
time: 1.4369730949401855
ちょっと待ってねがすべて出力されたあとで待ち時間に入った
ちょっと待ってね (1) → 待ち → (1)の結果 → ちょっと待ってね (2) → 待ち → (2)の結果 ではない
待ち時間が重なっている