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 重試可能造成重複下單。