网站首页 > 文章精选 正文
为什么我推荐你用httpx?
你是不是经常需要:
- 批量调用接口、测试接口稳定性?
- 发几十个请求跑数据分析?
- 想爬网页但速度太慢?
老牌 requests 在这些场景早就力不从心。而 httpx 是它的全新异步增强版:
特性 | requests | httpx |
异步请求 | 不支持 | 原生支持 |
HTTP/2 支持 | ||
请求池复用 | 部分支持 | 内置 |
与 requests API 一致 |
学习本来就不是一蹴而就的事,不过只要你肯练、敢用,坚持,你一定能看到变化!
1. 快速上手:同步请求 vs 异步请求
同步示例(和 requests 几乎一样):
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish
@File :D22.py
@Date :2025/6/23 20:53
@Author : malijie
"""
import json
import httpx
r = httpx.get("https://httpbin.org/get")
print(r.status_code)
print(json.dumps(r.json(), indent=2, ensure_ascii=False))
异步示例(适合并发):
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish
@File :D22.py
@Date :2025/6/23 20:53
@Author : malijie
"""
import json
import asyncio
import httpx
async def get_data():
async with httpx.AsyncClient() as client:
r = await client.get("https://httpbin.org/get")
print(r.status_code)
print(json.dumps(r.json(), indent=2, ensure_ascii=False))
asyncio.run(get_data())
2. 实战:高并发接口调用
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish
@File :D22.py
@Date :2025/6/23 20:53
@Author : malijie
"""
import json
import asyncio
import httpx
urls = [f"https://httpbin.org/get?i={i}" for i in range(10)]
async def fetch(url):
async with httpx.AsyncClient() as client:
r = await client.get(url)
print(f"{url} → {r.status_code}")
async def main():
await asyncio.gather(*[fetch(u) for u in urls])
asyncio.run(main())
实际测试:10个接口同时发出,总耗时小于 1 秒!
3. 进阶用法合集(最实用功能)
携带 Token / Headers
headers = {"Authorization": "Bearer YOUR_TOKEN"}
r = httpx.get("https://api.xxx.com/data", headers=headers)
POST JSON 请求
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish
@File :D22.py
@Date :2025/6/23 20:53
@Author : malijie
"""
import json
import httpx
url = "https://httpbin.org/post"
r = httpx.post(url, json={"user": "fish"})
print(json.dumps(r.json(), indent=2, ensure_ascii=False))
设置超时 / 重试
client = httpx.Client(timeout=httpx.Timeout(5.0, connect=2.0))
r = client.get("https://httpbin.org/delay/2")
代理请求
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish
@File :D22.py
@Date :2025/6/23 20:53
@Author : malijie
"""
import json
import httpx
url = "https://httpbin.org/post"
r = httpx.post(url, json={"user": "fish"})
print(json.dumps(r.json(), indent=2, ensure_ascii=False))
4. 配合 FastAPI 打造异步接口调用器
适合场景:平台系统 -> 多子系统接口触发器
from fastapi import FastAPI
import httpx
app = FastAPI()
@app.get("/multi-call")
async def multi_call():
async with httpx.AsyncClient() as client:
r1 = await client.get("http://api1.com/data")
r2 = await client.get("http://api2.com/status")
return {"api1": r1.json(), "api2": r2.json()}
用 uvicorn 来启动这个 FastAPI 应用
D22 是你的文件名(不加 .py)
app 是你定义的 FastAPI 实例名
--reload 是调试模式,修改代码会自动重启
浏览器或 Postman 访问接口访问地址:
http://127.0.0.1:8000/multi-call
将看到如下类似结构的 JSON 响应
{
"api1": {
"args": {
"i": "1"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Host": "httpbin.org",
"User-Agent": "python-httpx/0.24.1",
"X-Amzn-Trace-Id": "Root=1-685a8774-6fa70a8c7e3268e41ba360b7"
},
"origin": "103.100.176.119",
"url": "https://httpbin.org/get?i=1"
},
"api2": {
"args": {
"i": "2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Host": "httpbin.org",
"User-Agent": "python-httpx/0.24.1",
"X-Amzn-Trace-Id": "Root=1-685a8774-2ba4edb47ed0f82e7aa0b879"
},
"origin": "103.100.176.119",
"url": "https://httpbin.org/get?i=2"
}
}
5. 场景集锦(实用性超高)
场景 | 推荐用法 |
接口自动化测试 | 异步并发测试接口 |
API 并发采集(如爬虫、舆情) | async + gather |
多 API 聚合查询 | httpx.AsyncClient |
大量数据 POST 写入 | 异步 POST + json |
登录后请求(带 token) | headers + session |
总结一句话:
httpx = 异步 + 现代 + 更强大的 requests
只要你涉及接口调用,它就是你未来必备工具!
下期预告
《每天一个 Python 库:Flask 快速构建 Web 接口,接口开发不再难!》
点赞关注不迷路,后续更新更多自动化测试经验,我们一起成长!欢迎评论区留言!
- 上一篇: 如何高效实现API接口的自动化测试?
- 下一篇: 工厂模式+策略模式消除 if else 实战
猜你喜欢
- 2025-07-10 Vue3+Django4全新技术实战全栈项目|高清完结
- 2025-07-10 工厂模式+策略模式消除 if else 实战
- 2025-07-10 如何高效实现API接口的自动化测试?
- 最近发表
-
- Vue3+Django4全新技术实战全栈项目|高清完结
- 工厂模式+策略模式消除 if else 实战
- 每天一个 Python 库:httpx异步请求,让接口测试飞起来
- 如何高效实现API接口的自动化测试?
- 前端工程化:从“手忙脚乱”到“从容协作”的进化记
- 使用C#创建服务端Web API(c#开发web服务器)
- SpringBoot之旅第四篇-web开发(springboot做web项目)
- 一文读懂SpringMVC(一文读懂新型政策性金融工具)
- Rust Web编程:第十二章 在 Rocket 中重新创建我们的应用程序
- Apache Druid 数据摄取——本地数据和kafka流式数据 一篇文章看懂
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 编程题 (64)
- postgresql默认端口 (66)
- 数据库的概念模型独立于 (48)
- 产生系统死锁的原因可能是由于 (51)
- 数据库中只存放视图的 (62)
- 在vi中退出不保存的命令是 (53)
- 哪个命令可以将普通用户转换成超级用户 (49)
- noscript标签的作用 (48)
- 联合利华网申 (49)
- swagger和postman (46)
- 结构化程序设计主要强调 (53)
- 172.1 (57)
- apipostwebsocket (47)
- 唯品会后台 (61)
- 简历助手 (56)
- offshow (61)
- mysql数据库面试题 (57)