python network_error ai_generated true

httpx.HTTPStatusError: 对URL 'https://api.example.com/v1/data' 的客户端错误 '429 请求过多'

httpx.HTTPStatusError: Client error '429 Too Many Requests' for url 'https://api.example.com/v1/data'

ID: python/httpx-httpstatuserror-429

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-04-05首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

由于短时间内请求过多,服务器对客户端进行速率限制。

English

The server is rate-limiting the client due to excessive requests in a short time.

generic

解决方案

  1. 90% 成功率 Implement exponential backoff and retry logic
    import time
    for attempt in range(5):
        try:
            response = httpx.get('https://api.example.com/v1/data')
            response.raise_for_status()
            break
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 429:
                time.sleep(2 ** attempt)
            else:
                raise
  2. 60% 成功率 Add a custom User-Agent header to identify your application
    headers = {'User-Agent': 'MyApp/1.0'}
    httpx.get('https://api.example.com/v1/data', headers=headers)

无效尝试

常见但无效的做法:

  1. Retrying immediately with the same request 95% 失败

    Retrying without delay will likely hit the same rate limit again.

  2. Ignoring the error and continuing to send requests 80% 失败

    The server may temporarily block the client after repeated violations.