必须显式设置timeout,否则requests默认无限等待导致线程hang死;推荐使用元组形式timeout=(connect, read),并结合tenacity实现带退避的重试与熔断机制。
timeout
不设 timeout 时,requests 默认无限等待响应,一旦服务端卡住或网络中断,调用线程就彻底 hang 死。这不是“慢”,是“永远没结果”。生产环境绝对不能依赖默认行为。
正确做法是始终传入 timeout 元组:
response = requests.get(url, timeout=(3.0, 10.0))其中第一个值是连接超时(connect timeout),第二个是读取超时(read timeout)。连接超时建议 3–5 秒,读取超时按业务预期响应时间上浮 2–3 倍,比如正常返回要 800ms,设成 3.0 秒较稳妥。
timeout=5 是单数值写法,等价于 timeout=(5, 5),但连接和读取场景差异大,不推荐混用timeout=5,但无法区分是连不上还是连上了但迟迟不发数据proxy_read_timeout),需确保 requests 的读取超时小于它,否则可能被中间件先断连tenacity 实现带退避的重试逻辑手动写 while 循环 + sleep 容易漏掉异常类型、重复代码多、退避策略粗糙。直接用 tenacity 库更可靠,它专为重试设计,支持指数退避、 jitter、停止条件等关键能力。
安装与基础用法:
pip install tenacity
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type@retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=1, max=10), retry=retry_if_exception_type((requests.Timeout, requests.ConnectionError)) ) def fetch_data(url): return requests.get(url, timeout=(3, 10))
Timeout / ConnectionError),不重试 HTTPError(如 404、500),那是业务问题,重试无意义wait_exponential 的 min 和 max 防止退避时间过长或过短;multiplier=1 表示从 1s 开始,依次 1s → 2s → 4sretry_if_result 配合检查 response.status_code
重试本身会加剧下游压力。当接口连续失败时,盲目重试可能把雪崩风险翻倍。必须配合熔断机制,在故障持续期间主动拒绝请求,给下游恢复时间。
tenacity 自带简单熔断(stop_after_delay),但生产级建议用 pybreaker 或自建状态标记。一个轻量方案是用共享变量记录最近失败次数:
import time _last_failure_time = 0 _failure_count = 0def is_circuit_open(): now = time.time() if now - _last_failure_time > 60: # 1分钟内清零计数 _failure_count = 0 _last_failure_time = now return _failure_count >= 5
is_circuit_open(),返回 True 就直接抛异常或返回降级数据,不发起真实调用_failure_count,失败则递增threading.local() 或 concurrent.futures.ThreadPoolExecutor 配合锁logging 并捕获真实异常链很多“超时重试无效”问题,其实是底层抛了别的异常(如 DNS 解析失败、SSL 握手错误、证书过期),但被重试装饰器吞掉或日志没打全,导致误判为网络不稳定。
启用 requests 日志并打印完整异常栈:
import logging import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retrylogging.basicConfig(level=logging.DEBUG) logging.getLogger("urllib3").setLevel(logging.DEBUG)
同时配置 urllib3 的重试(仅限连接层,不影响业务逻辑重试)
session = requests.Session() retry_strategy = Retry( total=0, # 关闭 urllib3 自身重试,由 tenacity 统一管 connect=0, read=0, ) adapter = HTTPAdapter(max_retries=retry_strategy) session.mount("http://", adapter) session.mount("https://", adapter)
DEBUG:urllib3.connectionpool:Starting new HTTP connection 表示开始建连,卡在这里说明是 DNS 或防火墙问题Read timed out 但没后续日志,说明是读取超时;若卡在 Connecting to 后无反应,大概率是 connect 超时或中间网络设备拦截SSLError: certificate verify failed)不会触发 requests.Timeout,需单独捕获 requests.exceptions.SSLError
重试不是万能胶水,超时也不是越大越好。真正稳定的关键,是分清哪类失败可重试、哪类该熔断、哪类必须人工介入——而这一切的前提,是看懂日志里那几行真实的错误路径。