我正在尝试从 Spotify 的 API 中提取音频功能。我有一个包含大约 280,000 首歌曲的数据集,但不包含我想要的音频功能,因此我从数据集中的每首歌曲中提取曲目 ID,并分批发送 50 首歌曲的请求,请求之间有 1 秒的延迟。昨天,我毫无问题地获取了大约 100,000 首歌曲的音频功能,但随后它开始抛出错误 429,我知道这是速率限制错误。然而,我现在已经等了一整天才再次打电话,现在每次我收到的都是错误 429,即使我将批量大小更改为 25 首歌曲并且请求之间有 5 秒的延迟。 很好奇我的代码中是否有什么错误导致 Spotify 的 API 对我不满意。全部用Python完成。
#track_uri is column in my dataframe and I split it into track_id then turn into list and split into batches of 50
df['track_id'] = df['track_uri'].str.replace('spotify:track:', '', regex=False)
track_ids = df['track_id'].tolist()
batches = [track_ids[i:i + 50] for i in range(0, len(track_ids), 50)]
###token info
def get_track_info(header, track_ids):
ids = ','.join(track_ids)
url = f'https://api.spotify.com/v1/audio-features/?ids={ids}'
r = get(url, headers=header)
return r.json()
for i, batch in enumerate(batches, start=1):
track_info = get_track_info(header, batch)
filename = f'audio_features_{i}.json'
with open(filename, 'w') as f:
json.dump(track_info, f, indent=4)
sleep(1)
您的代码没有任何问题,但似乎您不遵守 Spotify 开发人员文档中指定的速率限制:https://developer.spotify.com/documentation/web-api/concepts/rate-limits
The header of the 429 response will normally include a Retry-After header with a value in seconds.
您可以将其添加到代码中以减慢进程。
另请参阅:https://community.spotify.com/t5/Spotify-for-Developers/Web-API-ratelimit/td-p/5330410