requests库测试时常用的东西全部都用代码举例写出,一定把requests库写完
时间: 2025-07-20 22:19:07 浏览: 1
<think>我们被要求提供Python requests库的完整使用示例,特别是用于测试的代码示例。由于用户提到了"testing examples",我们将重点展示如何使用requests库进行HTTP请求,并包括一些测试中常见的场景,如设置请求头、处理响应、异常处理等。同时,为了完整性,我们会覆盖GET、POST等常用方法,以及会话维持、代理设置等高级用法。
注意:在测试中,我们通常需要模拟各种情况,包括成功响应、错误响应(如404、500)、超时等。此外,我们还会展示如何检查响应内容,这对于测试非常重要。
由于requests库本身不提供测试框架,但可以与unittest、pytest等测试框架结合使用。这里我们主要展示requests的使用,测试框架的整合可能需要额外的代码。
下面是一个完整的示例脚本,包含注释说明:</think>### Python requests 库完整使用指南
以下是 `requests` 库的完整使用示例,包含测试中常见的场景:
#### 1. 基础 GET 请求
```python
import requests
# 简单 GET 请求
response = requests.get('https://api.example.com/data')
print(f"状态码: {response.status_code}")
print(f"响应内容: {response.text}")
# 带参数请求
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://api.example.com/search', params=params)
```
#### 2. POST 请求与 JSON 处理
```python
# 表单数据提交
payload = {'username': 'admin', 'password': 'secret'}
response = requests.post('https://api.example.com/login', data=payload)
# JSON 数据提交
headers = {'Content-Type': 'application/json'}
data = {'title': '测试文章', 'content': '请求库示例'}
response = requests.post('https://api.example.com/posts', json=data, headers=headers)
# 解析 JSON 响应
if response.status_code == 200:
json_data = response.json()
print(f"创建的文章ID: {json_data['id']}")
```
#### 3. 异常处理(测试关键)
```python
try:
response = requests.get('https://api.example.com/data', timeout=5)
response.raise_for_status() # 自动检查4xx/5xx错误
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.HTTPError as err:
print(f"HTTP错误: {err}")
except requests.exceptions.RequestException as err:
print(f"请求异常: {err}")
```
#### 4. 会话维持(保持cookies)
```python
with requests.Session() as session:
# 登录保持会话
session.post('https://api.example.com/login', data={'user': 'test', 'pass': 'test'})
# 后续请求自动携带cookies
profile = session.get('https://api.example.com/profile')
print(f"用户资料: {profile.json()}")
```
#### 5. 测试常用功能
```python
# 自定义请求头
headers = {
'User-Agent': 'Mozilla/5.0',
'Authorization': 'Bearer token123'
}
# 文件上传
files = {'file': open('report.xlsx', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)
# 代理设置
proxies = {'http': 'http://10.10.1.10:3128', 'https': 'https://10.10.1.10:1080'}
response = requests.get('http://external.site.com', proxies=proxies)
# 响应验证
assert response.status_code == 200
assert 'success' in response.json()['status']
assert response.elapsed.total_seconds() < 2.0 # 响应时间验证
```
#### 6. 高级用法
```python
# 流式下载大文件
with requests.get('https://example.com/large.zip', stream=True) as r:
with open('large.zip', 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
# SSL 证书验证(测试环境可关闭)
response = requests.get('https://api.example.com', verify=False) # 生产环境不推荐
# 自定义重定向处理
response = requests.get('http://github.com', allow_redirects=False)
print(f"重定向状态: {response.status_code}")
```
#### 7. 测试用例示例(使用unittest)
```python
import unittest
import requests
from unittest.mock import patch
class TestAPI(unittest.TestCase):
@patch('requests.get')
def test_user_endpoint(self, mock_get):
# 模拟响应
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {'id': 1, 'name': '测试用户'}
# 调用被测代码
response = requests.get('https://api.example.com/users/1')
# 验证结果
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()['name'], '测试用户')
if __name__ == '__main__':
unittest.main()
```
### 最佳实践提示:
1. 始终添加超时参数(`timeout=5`)防止永久阻塞
2. 使用 `Session` 对象管理持久连接和 cookies
3. 生产环境必须启用 SSL 验证(`verify=True`)
4. 使用 `response.raise_for_status()` 自动处理错误状态码
5. 对于 JSON API,优先使用 `response.json()` 替代手动解析
通过结合这些代码示例和测试技术,您可以构建健壮的 API 测试套件。HyperAgent 等工具可以扩展测试能力,无需编写复杂脚本[^2]。
阅读全文
相关推荐


















