spotipy 高请求率

Spotipy high request rate

我目前正在开发一个小程序(主要是为我自己),它将获取我当前正在播放的歌曲并将其发送到数据库,这样我就可以制作一些图表来查看我在 X 中演奏艺术家的频率多少时间。 为此,我有以下代码:

import spotipy
import spotipy.util as util
from time import sleep

# My secret keys SO DON'T LEAK THEM
clientID = "CLIENT_ID"
clientSec = "CLIENT_SECRET"

while True:
    # The scopes defines how much you are allowed
    scope = "user-read-currently-playing"
    username = "USERNAME"   
    # Gets a token for spotify and should keep it updated
    token = util.prompt_for_user_token(username, scope, client_id=clientID, client_secret=clientSec, redirect_uri="http://localhost/Spotify/callback.php")
    sp = spotipy.Spotify(auth=token)    
    results = sp.currently_playing(market=None)

    progress = results["progress_ms"]
    playing = results["is_playing"]

    # Add the song after 15 seconds of playing
    if (progress >= 15000 and progress <= 15500 and playing):
        sendToDB()

    # Shows raw output that spotify returns
    print(results)
    sleep(0.4)

每 0.4 秒它会检查一首歌曲是否在一个时间范围内,以查看是否有新歌曲正在播放。 (我知道这是一个不好的方法,但我还没有找到更好的方法)。但是昨天我在 spotify 开发者门户网站上看到 2 个用户每天总共发出大约 300000 个请求。我不认为这是正常的,所以我尝试了一些不同的方法,只在令牌需要刷新时调用 util.prompt_for_user_token() 但问题是它只会 return 一个新结果令牌被刷新。所以我有两个问题:

  1. 有没有更好的方法来检查是否有新歌在播放,
  2. 有没有办法每 30 分钟请求一个新令牌,并且仍然从 spotify 获得实时结果?

还有 Recently Played Tracks 端点,您可以获得最近播放的 50 首曲目,而不是获取当前播放的单个曲目。

只有听过足够长的曲目(我认为是 30 秒)才会出现在该端点上(这是 Spotify 将其标记为播放的阈值)。

由于您知道一次播放的阈值是 30 秒,而端点 returns 的结果数是 50,这意味着您只需要大约每 50 * 30 秒检查一次就可以确定捕获每 25 分钟收听一次所有曲目。