当前位置: 首页 > 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.lryc.cn/news/592906.html

相关文章:

  • [特殊字符] Spring Boot 常用注解全解析:20 个高频注解 + 使用场景实例
  • Linux基础IO通关秘籍:从文件描述符到重定向
  • 龙虎榜——20250718
  • Redis高频面试题:利用I/O多路复用实现高并发
  • 服务端高并发方案设计
  • Linux操作系统之线程:分页式存储管理
  • ARINC818航空总线机载视频处理系统设计
  • stm32驱动双步进电机
  • NIO网络通信基础
  • 堆的实现,堆排序,咕咕咕
  • (5)颜色的灰度,亮度,对比度,透明度,都啥意思
  • ES v.s Milvus v.s PG
  • makefile -- part 1
  • Windows 安装WSL +Docker 部署通义千问大模型(同步解决Ubuntu启动命令闪退)
  • 白话深度学习:一副PPT入门CNN,ResNet和Transformer
  • ESP32-IDF LVGL UI 设计工具的使用
  • vs openssl编译提示无法打开文件“libssl.lib”或“libcrypto.lib”
  • 046_局部内部类与匿名内部类
  • NQA_路由自动切换实验(H3C)
  • 小记_想写啥写啥_实现行间的Latex公式_VScode始终折叠大纲
  • [Raspberry Pi]如何將無頭虛擬顯示器服務(headless display)建置在樹莓派的Ubuntu桌面作業系統中?
  • 学校同步时钟系统让时间精准统一
  • 美客多跨境电商平台怎么开店?美客多入驻门槛有哪些?
  • OOA(面向对象分析)深度解析:业务建模的核心方法论
  • 零售快销行业中线下巡店AI是如何颠覆传统计算机视觉识别的详细解决方案
  • ABAP ANALYZE_ACT_FIELDCAT 错误
  • 控制鼠标和键盘
  • C++ 程序设计考量表
  • 7.18 Java基础 |
  • 全国高等院校计算机基础教育研究会2025学术年会在西宁成功举办 ——高原论道启新程,数智融合育英才