Python 请求库:request和httpx的区别

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())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咬尾巴的猫在coding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值