Requests是Python生态中最流行的HTTP客户端库,由Kenneth Reitz开发维护,以“人性化的HTTP库”为设计理念,极大简化了HTTP请求的编写过程。相较于标准库urllib,Requests提供了更简洁的API、更智能的会话管理、更完善的异常体系、原生支持SSL验证、Cookie持久化、代理配置等企业级特性。
requests.get(url)即可完成基础请求requests.Session()实现登录态复用,避免重复认证开销在实际接口测试中,Requests常用于:
• 自动化测试脚本构建
• 接口契约验证(Swagger/OpenAPI对接)
• 性能压测前的数据准备
• Mock服务请求触发
• 日志采集与监控探针实现
• 第三方API集成测试
💡 网友经验:某金融公司接口测试平台将Requests作为核心请求引擎,配合pytest fixtures实现测试数据隔离,单次测试套件执行效率提升37%,错误定位时间缩短至分钟级。
Requests库已内置于Python 3.10+标准库的urllib3依赖中,但需单独安装Requests本身。推荐使用pip进行安装,确保环境纯净:
pip install requests
验证安装是否成功:
python -c "import requests; print(requests.__version__)"
输出2.31.0或更高版本即表示安装成功。当前最新稳定版为2.32.3(2026年3月数据)。
verify=False临时禁用(生产环境严禁使用)requests.adapters.DEFAULT_RETRIESresponse.encoding = 'utf-8'⚠️ 安全提醒:禁止在代码中硬编码verify=False,应通过环境变量或配置文件动态控制SSL验证策略。
Requests通过params参数自动构建查询字符串,避免手动拼接URL:
import requests
url = "https://api.example.com/search"
params = {"q": "python requests", "page": 1}
response = requests.get(url, params=params, timeout=10)
print(response.url) # 自动构建为 https://api.example.com/search?q=python+requests&page=1
当参数值包含特殊字符(如空格、中文)时,Requests会自动进行URL编码,无需开发者处理。
表单数据提交使用data参数:
payload = {"username": "testuser", "password": "123456"}
response = requests.post("https://api.example.com/login", data=payload)
JSON数据提交使用json参数(自动设置Content-Type为application/json):
payload = {"query": "SELECT * FROM users", "limit": 10}
response = requests.post("https://api.example.com/query", json=payload)
| 特性 | GET请求 | POST请求 |
|---|---|---|
| 参数位置 | URL查询字符串 | 请求体 |
| 数据长度限制 | 浏览器限制(通常2048字符) | 服务器限制(通常无硬性限制) |
| 缓存支持 | 可被缓存 | 默认不缓存 |
| 安全性 | 参数暴露在URL中 | 参数在请求体,相对安全 |
| 幂等性 | 幂等操作 | 非幂等操作 |
| 典型用途 | 数据查询、分页列表 | 数据提交、文件上传、登录 |
响应对象提供丰富属性用于结果校验:
response = requests.get("https://api.example.com/status")
print(response.status_code) # 200
print(response.headers['Content-Type']) # application/json
print(response.text) # 响应体字符串
print(response.json()) # 自动解析JSON响应(需Content-Type为application/json)
常见状态码处理示例:
if response.status_code == 200:
data = response.json()
print(f"成功获取{len(data)}条记录")
elif response.status_code == 404:
print("资源不存在,请检查URL")
elif response.status_code == 401:
print("未授权,请检查Token有效性")
else:
print(f"请求失败,状态码:{response.status_code}")
✅ 最佳实践:使用response.raise_for_status()自动抛出HTTPError异常,简化错误处理逻辑。
会话对象允许在多个请求间保持Cookie和连接池,显著提升性能:
session = requests.Session()
# 首次请求获取登录Cookie
session.post("https://api.example.com/login", data={"user": "test", "pass": "123"})
# 后续请求自动携带Cookie
profile = session.get("https://api.example.com/profile")
orders = session.get("https://api.example.com/orders")
会话对象还支持全局请求头设置:
session.headers.update({"Authorization": "Bearer your_token_here",
"User-Agent": "TestClient/1.0"})
企业内网常需通过代理访问外部API,Requests提供灵活代理支持:
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080",
}
response = requests.get("https://api.example.com", proxies=proxies, verify=False)
SSL验证策略可通过verify参数控制:
verify=True:默认行为,验证服务器证书verify=False:跳过验证(仅限测试环境)verify='/path/to/certfile':指定自定义CA证书路径基础超时设置:
response = requests.get(url, timeout=(5, 10)) # (连接超时5秒, 读取超时10秒)
使用requests.adapters.HTTPAdapter实现高级重试策略:
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
retries = Retry(total=3, backoff_factor=0.5, status_forcelist=[500,502,503,504])
session.mount('http://', HTTPAdapter(max_retries=retries))
session.mount('https://', HTTPAdapter(max_retries=retries))
Requests支持注册回调函数处理请求/响应生命周期:
def log_response(response, *args, **kwargs):
print(f"[{response.status_code}] {response.url}")
response = requests.get("https://api.example.com", hooks={'response': log_response})
该机制常用于统一日志记录、性能监控、错误重试等场景。
通过requests_toolbelt库实现请求过程完整记录:
from requests_toolbelt.utils import dump
response = requests.get("https://api.example.com")
data = dump.dump_all(response)
print(data.decode('utf-8'))
输出包含完整请求头、响应头、请求体、响应体,便于定位中间人攻击或编码问题。
解决方案:检查请求URL编码与响应解码一致性
params = {"query": "接口测试"}
response = requests.get(url, params=params, timeout=10)
response.encoding = 'utf-8' # 显式指定编码
典型原因:缺少User-Agent或Referer头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"Referer": "https://example.com"
}
response = requests.get(url, headers=headers)
常见原因:响应非标准JSON格式
try:
data = response.json()
except ValueError:
print("响应体非JSON格式,原始内容:", response.text)
💡 调试技巧:使用curl -v命令模拟请求,对比Python脚本输出,快速定位差异点。
创建fixtures管理测试环境:
import pytest
import requests
@pytest.fixture
def api_client():
session = requests.Session()
session.headers.update({"Authorization": "Bearer test_token"})
yield session
session.close()
def test_get_user_profile(api_client):
response = api_client.get("https://api.example.com/profile")
assert response.status_code == 200
data = response.json()
assert "username" in data
使用unittest.mock模拟网络请求,避免测试依赖外部服务:
from unittest.mock import patch
import requests
@patch('requests.get')
def test_search(mock_get):
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {"results": []}
response = requests.get("https://api.example.com/search")
assert response.status_code == 200
assert len(response.json()["results"]) == 0
结合time模块测量单次请求耗时:
import time
start = time.time()
response = requests.get("https://api.example.com/heavy")
end = time.time()
print(f"请求耗时:{end - start:.3f}秒")
print(f"响应大小:{len(response.content)}字节")
使用gevent实现并发请求模拟:
import gevent
from gevent import monkey
monkey.patch_all()
def fetch(url):
return requests.get(url).status_code
urls = ["https://api.example.com/endpoint"] * 100
jobs = [gevent.spawn(fetch, url) for url in urls]
gevent.joinall(jobs)
print(f"成功完成{sum(1 for j in jobs if j.value == 200)}次请求")
⚠️ 注意:并发测试需控制压力,避免对目标服务造成拒绝服务攻击(DoS)。
以下内容基于2026年3月Stack Overflow、知乎、CSDN等平台高频问题整理,提供可落地解决方案:
分页参数通常为page/size或offset/limit,推荐使用while循环自动遍历:
def fetch_all_pages(base_url, params=None):
all_data = []
params = params or {}
page = 1
while True:
params['page'] = page
response = requests.get(base_url, params=params)
data = response.json()
items = data.get('items', [])
if not items:
break
all_data.extend(items)
page += 1
return all_data
使用files参数传递文件对象:
files = {'file': ('report.pdf', open('report.pdf', 'rb'), 'application/pdf')}
response = requests.post(url, files=files)
支持同时上传多个文件:
files = [
('file1', ('a.txt', open('a.txt', 'rb'), 'text/plain')),
('file2', ('b.jpg', open('b.jpg', 'rb'), 'image/jpeg'))
]
response = requests.post(url, files=files)
使用requests内置认证机制:
response = requests.get(url, auth=('username', 'password'))
对于Token认证,推荐使用Session管理:
session = requests.Session()
session.headers.update({"Authorization": "Basic base64编码的用户名:密码"})
response = session.get(url)
直接访问session.cookies对象:
session = requests.Session()
session.post("https://api.example.com/login", data=payload)
print(session.cookies.get_dict()) # {'sessionid': 'abc123'}
单次请求设置:
headers = {"Content-Type": "application/json", "X-API-Key": "secret"}
response = requests.post(url, json=data, headers=headers)
全局设置(Session):
session = requests.Session()
session.headers.update({"User-Agent": "CustomClient/1.0"})
使用stream=True流式下载,避免内存溢出:
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open("large_file.zip", "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
指定客户端证书与私钥路径:
response = requests.get(url, cert=('/path/client_cert.pem', '/path/client_key.pem'))
添加完整浏览器头信息:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1"
}
response = requests.get(url, headers=headers)
Requests自动处理gzip/deflate压缩,但可强制解压:
response = requests.get(url, headers={"Accept-Encoding": "identity"})
print(response.text)
使用curl -v导出请求结构,再转换为Python代码:
curl -v -X POST https://api.example.com \
-H "Authorization: Bearer token" \
-H "Content-Type: application/json" \
-d '{"key":"value"}'
对比Python实现差异点,快速定位问题。
| 工具 | 适用场景 | 与Requests集成度 |
|---|---|---|
| Postman | 手动测试、API文档生成 | 可导出Python代码 |
| Apifox | 全流程API协作平台 | 支持Python SDK |
| JMeter | 高性能压力测试 | 需插件支持 |
| HttpRunner | 自动化测试框架 | 基于Requests封装 |
| Swagger | API文档管理 | 通过Requests验证契约 |
小型项目:直接使用pytest + requests,快速搭建测试脚本
中型项目:采用HttpRunner框架,支持数据驱动与用例管理
大型项目:构建自研测试平台,集成CI/CD流水线
健康检查:每5分钟请求基础接口(如/status)
性能监控:记录P50/P90/P99响应时间
错误告警:当4xx/5xx比例超过阈值时触发告警
{
"timestamp": "2026-03-25T14:30:00Z",
"endpoint": "/api/v1/users",
"status_code": 200,
"response_time_ms": 145,
"error_rate": 0.02,
"throughput": 1250
}
📝 网友还关心:Python Requests与AIOHTTP在异步测试中的性能对比、Requests在微服务测试中的最佳实践、接口测试覆盖率提升策略