0
Help us understand the problem. What are the problem?

posted at

updated at

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

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倍以上高速化できた

参考

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
0
Help us understand the problem. What are the problem?