aiohttp
● 成熟度:aiohttp是较早提供异步HTTP客户端和服务器功能的Python库之一。它完全基于asyncio,在社区中广泛使用,有丰富的文档和社区支持。
● 客户端会话:aiohttp强调使用ClientSession作为发起请求的主要方式,这是因为ClientSession支持连接复用、cookies存储等。在aiohttp中,创建一个ClientSession实例,然后使用这个会话发起GET、POST等请求是常见的模式。
import aiohttp
import asyncio
async def fetch_with_aiohttp(endpoint, headers, data):
async with aiohttp.ClientSession() as session:
async with session.post(endpoint, headers=headers, json=data) as response:
print(response.status)
print(await response.json())
httpx
● 现代和简洁:httpx是一个相对较新的库,它的API设计得更加现代和简洁。httpx旨在提供requests库的异步版本,同时保持与requests相似的API设计,使得对于熟悉requests的用户更加容易上手。
● 同步和异步:httpx同时支持同步和异步请求,这意味着你可以在同一个库中使用相同的API进行同步和异步HTTP操作。
import httpx
import asyncio
async def fetch_with_httpx(url, headers, data):
async with httpx.AsyncClient() as client:
response = await client.post(url, headers=headers, json=data)
print(response.status_code)
print(response.json())