Requests 和 HTTPX 都是 Python 中广泛使用的 HTTP 客户端库,但它们在设计理念、功能和性能上存在显著差异。以下是两者的详细对比:
具体功能对比:
1、 同步请求(基础用法)
Requests:
# request实现流式请求输出stream=True
import requests
request_data = {"request_id":"e8b75756659a4ad2a2677e28b620f965","current_time":"2025-04-01T00:00:00","deviceId":"","user_id":"991"}
headers = {"Content-Type": "application/json"}
url = 'http://test.csdn.com/api/csdn/data-agent'
#responses = requests.request("POST", url=url, headers=headers, json=request_data,stream=True)
#for response in responses.iter_lines(decode_unicode=True):
# print(response)
# 连接管理:用 with 语句确保资源释放;
# 流式请求可能长时间阻塞,需设置 timeout 参数
with requests.request("POST",url=url,headers=headers,json=request_data,stream=True,timeout=30) as responses:
for response in responses.iter_lines(decode_unicode=True):
print(response)
HTTPX:
import httpx
request_data = {"request_id":"e8b75756659a4ad2a2677e28b620f965","current_time":"2025-04-01T00:00:00","deviceId":"","user_id":"991"}
headers = {"Content-Type": "application/json"}
url = 'http://test.csdn.com/api/csdn/data-agent'
with httpx.Client() as client:
with client.stream(
method="POST",
url=url,
headers=headers,
json=request_data
) as response:
if response.status_code == 200:
for chunk in response.iter_lines():
if chunk:
print(chunk)
else:
print(f"Error: {response.status_code}, {response.text}")
2、异步支持(关键差异)
Requests:
不支持原生异步,需要配合线程池:
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor() as executor:
future = executor.submit(requests.get, 'https://api.example.com/data')
response = future.result()
HTTPX:
原生支持 async/await:
import httpx
import asyncio
async def fetch_data():
async with httpx.AsyncClient() as client:
response = await client.get('https://api.example.com/data')
return response.json()
asyncio.run(fetch_data())