我正在使用Python请求从Spotify API获取一些信息,在一些请求之后,我遇到了429错误,这表明请求限制已被超出。 Spotify文档中写道,当你遇到这个错误时,响应头中有一个Retry-After,你必须等待一段时间并再次请求,但我收到的响应头没有这样的东西。
这是代码:
url = f'https://api.spotify.com/v1/audio-features/{track_id}'
res = requests.get(url, headers=self.headers)
if res.ok:
return res.json()
if res.status_code == 429:
print("------------- 429 ----------------")
print(res.headers)
return None
这是响应头:
{
"content-type": "application/json; charset=utf-8",
"cache-control": "private, max-age=0",
"access-control-allow-origin": "*",
"access-control-allow-headers": "Accept, App-Platform, Authorization, Content-Type, Origin, Retry-After, Spotify-App-Version, X-Cloud-Trace-Context, client-token, content-access-token",
"access-control-allow-methods": "GET, POST, OPTIONS, PUT, DELETE, PATCH",
"access-control-allow-credentials": "true",
"access-control-max-age": "604800",
"content-encoding": "gzip",
"strict-transport-security": "max-age=31536000",
"x-content-type-options": "nosniff",
"date": "Mon, 22 Jul 2024 11:51:11 GMT",
"server": "envoy",
"Via": "HTTP/2 edgeproxy, 1.1 google",
"Alt-Svc": "h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000",
"Transfer-Encoding": "chunked"
}
您可能需要尝试,因为您不知道要等待多长时间,并且响应标头中没有
RETRY_AFTER
。传递一个重试对象以对不同类型的重试进行细粒度控制。
从
backoff_factor=2
开始,此重试对象配置为处理三次重试,延迟逐渐变长,在失败之前延迟 2, 4, 8...
秒。
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
retry_strategy = Retry(
total=3,
backoff_factor=2
)
adapter = HTTPAdapter(max_retries=retry_strategy)
http = requests.Session()
http.mount("https://", adapter)
http.mount("http://", adapter)
url = f'https://api.spotify.com/v1/audio-features/{track_id}'
res = http.get(url, headers=self.headers)
在我的示例中,
retry_strategy
总共 三次 重试,并在失败前逐渐延长延迟 2, 4, 8...
秒。