一、Python 实现 HTTP Client 的常见方式总览
Python 常见 HTTP Client 实现方式:
| 类型 | 代表库 | 是否异步 | 推荐程度 |
|---|---|---|---|
| 标准库 | urllib |
否 | (了解即可) |
| 第三方同步 | requests |
否 | |
| 第三方现代同步/异步 | httpx |
支持 | (强烈推荐) |
| 异步高性能 | aiohttp |
是 | |
| 框架内置 | FastAPI / Django 内部 client | 视情况 | 场景依赖 |
| 底层 | socket |
否 | (特殊场景) |
二、urllib(标准库)
1. 是什么?
Python 标准库自带的 HTTP 工具。
import urllib.request
不需要安装第三方库。
2. 有什么用?
- 基础 HTTP 请求
- 简单下载文件
- 受限环境下使用(如不能安装第三方库)
3. 怎么用?
python
import urllib.request
import json
url = "https://api.example.com/data"
req = urllib.request.Request(url, method="GET")
with urllib.request.urlopen(req) as response:
data = response.read()
print(json.loads(data))
POST 示例:
python
import urllib.parse
data = urllib.parse.urlencode({"key": "value"}).encode()
req = urllib.request.Request(url, data=data, method="POST")
4. 如何优雅地用?
❌ 不优雅点:
- API 复杂
- 异常处理繁琐
- JSON 解析不自动
- 没有 session 管理
建议:
- 仅用于脚本
- 不用于生产服务
5. 适用场景
- 无法安装第三方库
- 教学
- 简单脚本
三、requests(最常用同步方案)
1. 是什么?
Python 最流行的 HTTP 库。
pip install requests
2. 有什么用?
- 微服务调用
- 第三方 API 调用
- 简单同步 HTTP 请求
- 内部工具系统
3. 怎么用?
基本 GET
python
import requests
resp = requests.get("https://api.example.com/data")
print(resp.status_code)
print(resp.json())
POST
python
resp = requests.post(
"https://api.example.com/login",
json={"username": "pan", "password": "123"},
timeout=5
)
4. 如何优雅地用?
使用 Session 复用连接
python
session = requests.Session()
session.headers.update({
"Authorization": "Bearer token"
})
resp = session.get("https://api.example.com/data")
好处:
- TCP 连接复用
- 性能提升
- 统一 header 管理
设置 timeout(必须)
python
requests.get(url, timeout=(3, 10)) # (connect, read)
否则:
- 可能无限阻塞
- 生产事故常见坑
异常处理规范
python
try:
resp = requests.get(url, timeout=5)
resp.raise_for_status()
except requests.exceptions.Timeout:
...
except requests.exceptions.RequestException:
...
❌ requests 的问题
- 不支持原生 async
- 高并发场景性能差
- 不适合 IO 密集型服务
5. 适用场景
| 场景 | 是否推荐 |
|---|---|
| 内部工具 | |
| 管理后台 | |
| 高并发服务 | ❌ |
| 异步框架 | ❌ |
四、httpx(现代最佳实践)
强烈推荐 3 年经验工程师重点掌握
1. 是什么?
-
requests 的升级版
-
支持同步 + 异步
-
支持 HTTP/2
-
API 风格接近 requests
pip install httpx
2. 有什么用?
- 微服务调用
- 异步高并发系统
- 替代 requests
- Tornado / FastAPI 等场景
3. 怎么用?
同步用法
python
import httpx
with httpx.Client(timeout=5.0) as client:
resp = client.get("https://api.example.com/data")
print(resp.json())
异步用法(重点)
python
import httpx
import asyncio
async def main():
async with httpx.AsyncClient(timeout=5.0) as client:
resp = await client.get("https://api.example.com/data")
print(resp.json())
asyncio.run(main())
4. 如何优雅地用(重点)
1. 全局复用 Client
❌ 错误写法:
python
async def handler():
async with httpx.AsyncClient() as client:
await client.get(url)
这样每次都会新建连接池。
正确写法:
python
client = httpx.AsyncClient(timeout=5.0)
async def handler():
resp = await client.get(url)
2. 配置连接池
python
limits = httpx.Limits(
max_connections=100,
max_keepalive_connections=20
)
client = httpx.AsyncClient(limits=limits)
3. 分离连接超时
python
timeout = httpx.Timeout(
connect=3.0,
read=10.0,
write=5.0,
pool=3.0
)
4. 使用重试机制(结合 tenacity)
python
from tenacity import retry, stop_after_attempt
@retry(stop=stop_after_attempt(3))
async def fetch():
return await client.get(url)
5. 统一封装一层
推荐封装:
python
class HttpClient:
def __init__(self):
self.client = httpx.AsyncClient(timeout=5.0)
async def get(self, url, **kwargs):
resp = await self.client.get(url, **kwargs)
resp.raise_for_status()
return resp.json()
5. 适用场景
| 场景 | 是否推荐 |
|---|---|
| 微服务调用 | |
| 异步系统 | |
| 高并发 IO | |
| 替代 requests |
五、aiohttp(异步老牌选手)
1. 是什么?
早期 Python 异步 HTTP 主力库。
pip install aiohttp
2. 怎么用?
python
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get("https://api.example.com") as resp:
print(await resp.json())
asyncio.run(main())
3. 特点
| 优点 | 缺点 |
|---|---|
| 性能高 | API 不如 httpx 友好 |
| 社区成熟 | 与 requests 不兼容 |
4. 适用场景
- 老项目
- 纯 asyncio 系统
新项目更推荐 httpx。
六、如何优雅地设计 HTTP Client(架构层)
这是 3 年工程师需要掌握的部分。
1. 统一出口
不要在业务代码里到处写:
python
httpx.get(...)
应该:
python
from infra.http import http_client
await http_client.get(...)
2. 加指标埋点
python
start = time.perf_counter()
resp = await client.get(url)
cost = time.perf_counter() - start
记录:
- QPS
- P50 / P99
- error_rate
3. 熔断 & 限流
结合:
- tenacity(重试)
- aiobreaker(熔断)
- asyncio.Semaphore(限流)
4. 不要踩的坑
| 坑 | 说明 |
|---|---|
| 不设置 timeout | 生产事故高发 |
| 每次新建 client | 连接爆炸 |
| 不处理异常 | 上游抖动拖死系统 |
| 不做限流 | 被下游打死 |
七、选型建议总结
内部小工具
requests
微服务调用
httpx + 连接池 + 重试
高并发异步系统
httpx.AsyncClient
老 asyncio 项目
aiohttp
八、给 3 年工程师的进阶建议
你应该掌握的不只是用法,而是:
- HTTP 连接池原理
- TCP keepalive
- TIME_WAIT 问题
- DNS 解析缓存
- 超时分层设计(connect / read / pool)
- 上游依赖治理
九、最终推荐结论
如果你现在问:
2026 年 Python HTTP Client 推荐什么?
答案是:
httpx.AsyncClient
同步场景用:
httpx.Client
如果你愿意,我可以再给你一份:
- 面向生产的 HTTP Client 封装模板
- 高并发翻译系统 HTTP 调优实践
- Tornado + httpx 的最佳实践架构图
你现在的技术栈我大概了解一点,如果结合你的翻译高 IO 场景,我可以给你一版专门针对"高并发外部 API 调用"的优化方案。