正常速率限制为 600/5 分钟,但可以延长至 1200/5 分钟。我上周使用了这个脚本,它工作了几个小时,现在我不断收到 429 错误。
我认为脚本很好,但我可能缺少ratelimit
和backoff
库中的装饰器的某些内容,也许有人更熟悉这些库并看到我没有看到的逻辑错误。
# api_funcs.py module
import requests
from requests import ConnectionError
from ratelimit import limits, sleep_and_retry
from backoff import on_exception, expo
from pipeline_tools.helpers import get_key
KEY = get_key("API_key")
FIVE_MINUTES = 300 # Number of seconds in five minutes.
@sleep_and_retry # if we exceed the ratelimit imposed by @limits forces sleep until we can start again.
@on_exception(expo, ConnectionError, max_tries=5)
@limits(calls=1200, period=FIVE_MINUTES)
def call_api(url, api_key):
r = requests.get(url, auth=(api_key, ""))
if not (r.status_code == 200 or r.status_code == 404):
r.raise_for_status()
elif r.status_code == 404:
return dict({"error": "not found"})
else:
return r.json()
def company_basic_search(comp_code):
return call_api(url=API_BASE_URL+"/company/"+comp_code, api_key=KEY)
# [list of 200,000 company codes]
comp_codes = ['XXX1','XXX2','XXX3']
for code in comp_codes:
basic_profile_resource = company_basic_search(comp_code=code)
# if-elif-else flow inserting the object in error table if 404 or in other table if 200.
我不断得到一个
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 429 Client Error: Too Many Requests for url: ...
我的逻辑有什么问题,或者这可能是在 API 方面?