LoginSignup
1
1

More than 1 year has passed since last update.

requestsで非同期Asyncリクエスト【HTTPX】

Last updated at Posted at 2022-04-30

requestsをインストール

pip install httpx

requestsをインポート

150個のリクエストを作成します。

import httpx as requests
from asyncio import run, gather

urls = [f"https://pokeapi.co/api/v2/pokemon/{n}" for n in range(1, 151)]

同期(Sync)リクエスト 処理時間8.8秒

def sync_func():
    print([requests.get(u) for u in urls])

sync_func()

image.png

非同期(Async)リクエスト 処理時間0.7秒

async def async_func():
    async with requests.AsyncClient() as client:
        tasks = [client.get(u) for u in urls]
        print(await gather(*tasks, return_exceptions=True))

run(async_func())

image.png

まとめ

  • 非同期リクエストにすることで10倍以上高速化できた

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1