Pythonで非同期リクエストを行う際、requestsとaiohttpの2つのライブラリがよく使われます。これらのライブラリは、非同期通信を行うための異なるアプローチを提供します。
requestsは、Pythonの標準的なHTTPクライアントライブラリで、シンプルで直感的なAPIを提供します。しかし、requestsは同期的なライブラリであり、非同期処理を行うためには追加の手段が必要です。
一方、aiohttpは非同期I/OをサポートするHTTPクライアント/サーバライブラリで、asyncioと組み合わせて使用することで非同期通信を実現します。
以下に、requestsとaiohttpを使用した非同期リクエストのコード例を示します。
# requestsを使用した例
import requests
from concurrent.futures import ThreadPoolExecutor
def fetch(url):
return requests.get(url)
with ThreadPoolExecutor() as executor:
future = executor.submit(fetch, 'http://httpbin.org/get')
response = future.result()
print(response.json())
# aiohttpを使用した例
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://httpbin.org/get')
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
これらのコード例からわかるように、requestsを使用した場合はconcurrent.futuresモジュールを使用して非同期処理を行います。一方、aiohttpを使用した場合はasyncioモジュールを使用して非同期処理を行います。
これらの違いを理解することで、Pythonで非同期リクエストを行う際の適切なライブラリ選択に役立つでしょう。.