在python中自动重试遭遇http 429限流的api调用,最稳健的做法是使用 tenacity 库。通过配置 retry_if_exception_type 捕获异常并配合 wait_fixed 或 wait_random_exponential 设置等待时间,可以优雅地处理限流。

如何配置基于状态码的自定义重试逻辑?
要实现针对特定状态码(如429)的重试,需要定义一个继承自 Exception 的类来包装响应,并在 tenacity 中指定该异常类型作为重试条件。

import requests
from tenacity import retry, stop_after_attempt, wait_fixed, retry_if_exception_type
class RateLimitError(Exception):
pass
@retry(
stop=stop_after_attempt(3),
wait=wait_fixed(2),
retry=retry_if_exception_type(RateLimitError)
)
def fetch_data(url):
response = requests.get(url)
if response.status_code == 429:
raise RateLimitError("Rate limit exceeded")
return response.json()
try:
data = fetch_data('https://api.example.com/data')
print(data)
except Exception as e:
print(f"Failed: {e}")如何实现指数退避策略以应对突发流量?
当面对不确定的限流阈值时,使用指数退避策略比固定等待更有效。它能让请求间隔随重试次数呈指数增长,从而降低再次触发限流的概率。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;

from tenacity import retry, stop_after_attempt, wait_exponential
@retry(
stop=stop_after_attempt(5),
wait=wait_exponential(multiplier=1, min=4, max=10)
)
def robust_fetch(url):
response = requests.get(url)
response.raise_for_status()
return response.json()如果API返回了Retry-After头信息该如何处理?
许多API会在429响应中包含 Retry-After 头,指示具体的等待秒数。我们可以解析这个头信息来动态调整等待时间,而不是依赖固定的退避策略。

















