python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python HTTP Client

Python 实现HTTP Client 的常见方式总览

作者:破烂pan

本文总结了Python实现HTTPClient的常见方式,包括urllib、requests、httpx、aiohttp等库的优缺点和适用场景,同时,还介绍了如何优雅地设计HTTPClient,并给出了选型建议和进阶建议,感兴趣的朋友跟随小编一起看看吧

一、Python 实现 HTTP Client 的常见方式总览

Python 常见 HTTP Client 实现方式:

类型代表库是否异步推荐程度
标准库urllib(了解即可)
第三方同步requests
第三方现代同步/异步httpx支持(强烈推荐)
异步高性能aiohttp
框架内置FastAPI / Django 内部 client视情况场景依赖
底层socket(特殊场景)

二、urllib(标准库)

1. 是什么?

Python 标准库自带的 HTTP 工具。

import urllib.request

不需要安装第三方库。

2. 有什么用?

3. 怎么用?

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

4. 如何优雅地用?

❌ 不优雅点:

建议:

5. 适用场景

三、requests(最常用同步方案)

1. 是什么?

Python 最流行的 HTTP 库。

pip install requests

2. 有什么用?

3. 怎么用?

基本 GET

import requests
resp = requests.get("https://api.example.com/data")
print(resp.status_code)
print(resp.json())

POST

resp = requests.post(
    "https://api.example.com/login",
    json={"username": "pan", "password": "123"},
    timeout=5
)

4. 如何优雅地用?

使用 Session 复用连接

session = requests.Session()
session.headers.update({
    "Authorization": "Bearer token"
})
resp = session.get("https://api.example.com/data")

好处:

设置 timeout(必须)

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:
    ...

❌ requests 的问题

5. 适用场景

场景是否推荐
内部工具
管理后台
高并发服务
异步框架

四、httpx(现代最佳实践)

强烈推荐 3 年经验工程师重点掌握

1. 是什么?

pip install httpx

2. 有什么用?

3. 怎么用?

同步用法

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

4. 如何优雅地用(重点)

1. 全局复用 Client

❌ 错误写法:

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)

2. 配置连接池

limits = httpx.Limits(
    max_connections=100,
    max_keepalive_connections=20
)
client = httpx.AsyncClient(limits=limits)

3. 分离连接超时

timeout = httpx.Timeout(
    connect=3.0,
    read=10.0,
    write=5.0,
    pool=3.0
)

4. 使用重试机制(结合 tenacity)

from tenacity import retry, stop_after_attempt
@retry(stop=stop_after_attempt(3))
async def fetch():
    return await client.get(url)

5. 统一封装一层

推荐封装:

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. 怎么用?

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. 适用场景

新项目更推荐 httpx。

六、如何优雅地设计 HTTP Client(架构层)

这是 3 年工程师需要掌握的部分。

1. 统一出口

不要在业务代码里到处写:

httpx.get(...)

应该:

from infra.http import http_client
await http_client.get(...)

2. 加指标埋点

start = time.perf_counter()
resp = await client.get(url)
cost = time.perf_counter() - start

记录:

3. 熔断 & 限流

结合:

4. 不要踩的坑

说明
不设置 timeout生产事故高发
每次新建 client连接爆炸
不处理异常上游抖动拖死系统
不做限流被下游打死

七、选型建议总结

内部小工具

requests

微服务调用

httpx + 连接池 + 重试

高并发异步系统

httpx.AsyncClient

老 asyncio 项目

aiohttp

八、给 3 年工程师的进阶建议

你应该掌握的不只是用法,而是:

  1. HTTP 连接池原理
  2. TCP keepalive
  3. TIME_WAIT 问题
  4. DNS 解析缓存
  5. 超时分层设计(connect / read / pool)
  6. 上游依赖治理

九、最终推荐结论

如果你现在问:

2026 年 Python HTTP Client 推荐什么?

答案是:

httpx.AsyncClient

同步场景用:

httpx.Client

如果你愿意,我可以再给你一份:

你现在的技术栈我大概了解一点,如果结合你的翻译高 IO 场景,我可以给你一版专门针对“高并发外部 API 调用”的优化方案。

到此这篇关于Python 实现 HTTP Client 的常见方式的文章就介绍到这了,更多相关Python HTTP Client内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文