如何写python requests?
B站讲的最好的python接口自动化测试完整版项目实战教程,pytest自动化测试框架,接口自动环境测试框架封装
使用 Python Requests 库发送 HTTP 请求
Python 的 requests
库是用于发送 HTTP 请求的流行工具,比 urllib
更简单易用。以下是各种常见 HTTP 请求的写法:
安装 Requests
首先确保已安装 requests 库:
bash
pip install requests
基本 GET 请求
python
import requests# 简单 GET 请求 response = requests.get('https://api.example.com/data')# 带参数的 GET 请求 params = {'key1': 'value1', 'key2': 'value2'} response = requests.get('https://api.example.com/data', params=params)# 打印响应 print(response.status_code) # HTTP 状态码 print(response.text) # 响应内容
基本 POST 请求
python
# 简单 POST 请求 data = {'key': 'value'} response = requests.post('https://api.example.com/post', data=data)# 发送 JSON 数据 import json json_data = {'key': 'value'} response = requests.post('https://api.example.com/post', json=json_data)# 带 headers 的 POST 请求 headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer token'} response = requests.post('https://api.example.com/post', json=json_data, headers=headers)
其他 HTTP 方法
python
# PUT 请求 response = requests.put('https://api.example.com/put', data={'key': 'value'})# DELETE 请求 response = requests.delete('https://api.example.com/delete')# PATCH 请求 response = requests.patch('https://api.example.com/patch', data={'key': 'value'})
处理响应
python
response = requests.get('https://api.example.com/data')# 响应内容 print(response.text) # 文本格式 print(response.json()) # 如果响应是 JSON,转换为字典 print(response.content) # 二进制格式# 响应头 print(response.headers) print(response.headers['Content-Type'])# 状态码 print(response.status_code) response.raise_for_status() # 如果请求失败(4xx, 5xx),抛出异常
高级用法
1. 超时设置
python
# 设置超时时间(秒) response = requests.get('https://api.example.com/data', timeout=5)
2. 会话对象(Session)
python
# 创建会话(可以保持 cookies 和配置) session = requests.Session() session.headers.update({'Authorization': 'Bearer token'}) response = session.get('https://api.example.com/data')
3. 文件上传
python
files = {'file': open('report.xls', 'rb')} response = requests.post('https://api.example.com/upload', files=files)
4. 代理设置
python
proxies = {'http': 'http://10.10.1.10:3128','https': 'http://10.10.1.10:1080', } response = requests.get('https://api.example.com/data', proxies=proxies)
5. SSL 证书验证
python
# 禁用 SSL 验证(不推荐生产环境使用) response = requests.get('https://api.example.com/data', verify=False)# 使用自定义证书 response = requests.get('https://api.example.com/data', verify='/path/to/cert.pem')
错误处理
python
try:response = requests.get('https://api.example.com/data', timeout=5)response.raise_for_status() # 检查请求是否成功data = response.json() except requests.exceptions.RequestException as err:print(f"请求错误: {err}") except ValueError as err:print(f"JSON 解析错误: {err}")
示例:完整的 API 调用
python
import requestsdef get_user_data(user_id):try:url = f"https://api.example.com/users/{user_id}"headers = {'Authorization': 'Bearer your_access_token','Accept': 'application/json'}response = requests.get(url, headers=headers, timeout=10)response.raise_for_status()return response.json()except requests.exceptions.HTTPError as http_err:print(f"HTTP 错误: {http_err}")except requests.exceptions.RequestException as req_err:print(f"请求异常: {req_err}")except ValueError as json_err:print(f"JSON 解析错误: {json_err}")return None# 使用示例 user_data = get_user_data(123) if user_data:print(user_data)
这些是 requests
库的基本和常见用法,可以满足大多数 HTTP 请求需求。
B站讲的最好的python接口自动化测试完整版项目实战教程,pytest自动化测试框架,接口自动环境测试框架封装