1. requests库概述与核心价值
requests是Python生态中最受欢迎的HTTP客户端库,每天在数百万项目中处理着数以亿计的Web请求。作为urllib3的封装,它用更人性化的API设计让HTTP交互变得简单直观。在实际开发中,无论是爬虫数据采集、API接口调试,还是微服务通信,requests都展现出极高的实用性。
这个库的核心优势在于:
- 极简的API设计(如
requests.get()只需一行代码) - 自动化的内容解码(自动处理gzip/deflate压缩)
- 连接池复用提升性能
- 完善的超时重试机制
- 支持文件上传、Cookie持久化等高级特性
2. 基础请求方法与响应处理
2.1 GET请求实战
最基本的GET请求示例:
import requests response = requests.get('https://api.github.com/events') print(response.status_code) # 200 print(response.headers['Content-Type']) # 'application/json'关键响应属性解析:
text:自动解码的字符串内容(根据响应头猜测编码)content:原始字节数据(适合非文本内容)json():自动解析JSON响应(需确认Content-Type正确)status_code:HTTP状态码(200/404/500等)
2.2 POST请求参数传递
表单提交示例:
payload = {'key1': 'value1', 'key2': 'value2'} r = requests.post('https://httpbin.org/post', data=payload) print(r.text)JSON数据提交(推荐方式):
import json payload = {'some': 'data'} r = requests.post('https://httpbin.org/post', json=payload)注意:使用
json参数会自动设置Content-Type为application/json,且会序列化字典对象
3. 高级配置与性能优化
3.1 会话对象Session
重复创建连接会带来性能损耗,正确做法是使用Session:
with requests.Session() as s: s.get('https://httpbin.org/cookies/set/sessioncookie/123456789') response = s.get('https://httpbin.org/cookies') print(response.text) # 会保持cookiesSession的核心优势:
- 持久化cookies(如登录态保持)
- 连接池复用(TCP连接复用)
- 统一配置(headers/auth等)
3.2 超时与重试策略
必须设置的超时参数(单位秒):
requests.get('https://github.com', timeout=(3.05, 27))- 第一个数字是连接超时
- 第二个是读取超时
自定义重试策略:
from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry session = requests.Session() retries = Retry( total=3, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504] ) session.mount('https://', HTTPAdapter(max_retries=retries))4. 常见问题排查指南
4.1 429 Too Many Requests处理
当遇到429状态码时,应该:
- 检查请求频率是否符合API限制
- 添加延迟时间(time.sleep)
- 使用指数退避算法:
import time from random import random def exponential_backoff(retries): return min(60, (2 ** retries) + random()) retry_count = 0 while retry_count < 5: response = requests.get(url) if response.status_code != 429: break wait_time = exponential_backoff(retry_count) time.sleep(wait_time) retry_count += 14.2 SSL证书验证问题
开发环境可临时关闭验证(生产环境严禁):
requests.get('https://example.com', verify=False)更安全的做法是指定CA证书路径:
requests.get('https://example.com', verify='/path/to/certfile.pem')5. 实战技巧与性能调优
5.1 流式处理大响应
对于大文件下载,使用流式模式避免内存溢出:
with requests.get('https://example.com/bigfile', stream=True) as r: r.raise_for_status() with open('bigfile', 'wb') as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk)5.2 代理配置方案
通过代理发送请求:
proxies = { 'http': 'http://10.10.1.10:3128', 'https': 'http://10.10.1.10:1080', } requests.get('http://example.org', proxies=proxies)5.3 请求耗时分析
通过elapsed属性分析请求各阶段耗时:
r = requests.get('https://api.github.com') print(f"DNS解析: {r.elapsed.resolve}ms") print(f"TCP连接: {r.elapsed.connect}ms") print(f"请求发送: {r.elapsed.send}ms") print(f"等待响应: {r.elapsed.wait}ms") print(f"总耗时: {r.elapsed.total_seconds()}s")6. 最佳实践与安全建议
- 始终设置超时(避免阻塞)
- 生产环境必须启用SSL验证
- 敏感信息不要放在URL参数中
- 对大响应使用stream模式
- 合理设置User-Agent头
- 监控API调用频率(防封禁)
- 使用环境变量管理认证信息
对于高频访问场景,建议:
- 采用异步请求(aiohttp)
- 实现请求队列和速率限制
- 考虑使用专业代理服务
- 建立完善的日志监控系统