当前位置: 首页 > news >正文

如何写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自动化测试框架,接口自动环境测试框架封装

 

http://www.dtcms.com/a/286817.html

相关文章:

  • [Linux]如何設置靜態IP位址?
  • LangChain 源码剖析(七)RunnableBindingBase 深度剖析:给 Runnable“穿衣服“ 的装饰器架构
  • Vuex 基本概念
  • Java HashMap高频面试题深度解析
  • Redis高频面试题:利用I/O多路复用实现高并发
  • 在java后端项目中,controller、dal、service的作用是什么?
  • 从 0 安装 Label Studio:搭建可后台运行的数据标注平台(systemd 实践
  • 微服务项目总结
  • 【c++】中也有floor函数吗?他与JavaScript中的floor有啥区别?
  • 【iOS】消息传递和消息转发
  • Ubuntu系统下快速体验iperf3工具(网络性能测试)
  • CAN通信静默模式的原理与应用
  • 【JAVA】JVM内存泄漏围剿终极指南:Arthas在线诊断 + MAT内存分析完整链路
  • 代码随想录算法训练营第二十四天
  • 中国工业RFID前三品牌
  • 片上网络(NoC)拓扑结构比较
  • LeetCode 88 - Merge Sorted Array 合并有序数组
  • 策略模式+工厂模式(案例实践易懂版)
  • 半小时部署本地deepseek【1】
  • HTTP/2:突破性能瓶颈的Web传输革命
  • 低代码可视化工作流的系统设计与实现路径研究
  • 开启modbus tcp模拟调试
  • C++并发编程-14. 利用栅栏实现同步
  • 嵌入式系统内核镜像相关(十六)
  • Vue中使用vue-3d-model实现加载3D模型预览展示
  • docker命令参数详解
  • 数字化转型:概念性名词浅谈(第三十二讲)
  • 基础密码协议
  • Python os 模块:系统操作的 “百宝箱”
  • Java编程规范(简约版)