forked from Ikalus1988/MisakaNet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlesson-api-rate-limit-handling.json
More file actions
15 lines (15 loc) · 1.24 KB
/
Copy pathlesson-api-rate-limit-handling.json
File metadata and controls
15 lines (15 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"task_id": "lesson-api-rate-limit-handling",
"title": "API 请求限流 (Rate Limit) 处理方案",
"domain": "devops",
"tags": [
"api",
"rate-limit",
"retry",
"429"
],
"problem": "调用第三方 API 时返回 HTTP 429(Too Many Requests)或 403(被限流)。自动化脚本因未处理限流而中断。",
"solution": "```python\nimport time\nimport requests\n\ndef api_call_with_retry(url, headers, max_retries=5):\n for i in range(max_retries):\n resp = requests.get(url, headers=headers)\n \n if resp.status_code == 200:\n return resp.json()\n \n if resp.status_code == 429:\n wait = int(resp.headers.get(\"Retry-After\", 2 ** i))\n print(f\"限流,等待 {wait} 秒后重试...\")\n time.sleep(wait)\n continue\n \n # 其他错误不重试\n resp.raise_for_status()\n \n raise Exception(f\"超过最大重试次数: {url}\")\n\n# GitHub API 特殊:检查剩余配额\nresp = requests.get(\"https://api.github.com/rate_limit\")\ndata = resp.json()\nprint(f\"剩余: {data['rate']['remaining']}/{data['rate']['limit']}\")\n```",
"source": "lessons/contrib/api-rate-limit-handling.md",
"test_cmd": ""
}