HTTP 请求与错误重试
带超时和重试的请求写法,别让脚本卡死。
模板正文
import httpx
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, max=10))
def fetch(url: str) -> dict:
resp = httpx.get(url, timeout=10.0, headers={"User-Agent": "mybot/1.0"})
resp.raise_for_status()
return resp.json()
try:
data = fetch("https://api.example.com/items")
except httpx.HTTPStatusError as e:
print("状态码异常", e.response.status_code)
except httpx.TimeoutException:
print("超时,稍后重试")怎么用
调用第三方接口时使用。
使用要点
- 必须设 timeout,否则对方不响应时脚本会一直挂着。
- 只重试幂等请求(GET),POST 重试可能造成重复下单。