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