You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spotipy认证出现401错误,程序认证故障求助

解决Spotipy认证失效问题

以下是针对你遇到的认证过期、移除应用后无法重新授权问题的具体修复方案:

1. 修复Token自动刷新机制

你的代码手动获取access_token但未处理过期刷新,且未利用Spotipy内置的自动认证管理功能。修改认证逻辑如下:

#### ------------------------------ CONEXION API SPOTIFY ------------------------------ ####
#### ---------------------------------------------------------------------------------- ####

redirectURI = 'http://google.com/'
# 必须添加所需权限,否则无法调用播放相关接口
required_scopes = "user-read-currently-playing user-modify-playback-state"

# 初始化OAuth对象,指定缓存路径,自动处理token缓存与刷新
oauth_object = spotipy.SpotifyOAuth(
    client_id=clientID,
    client_secret=clientSecret,
    redirect_uri=redirectURI,
    scope=required_scopes,
    cache_path=".cache"  # 缓存文件存储token,避免重复授权
)

# 使用auth_manager创建spotify对象,自动处理token刷新
spotifyObject = spotipy.Spotify(auth_manager=oauth_object)

try:
    user = spotifyObject.current_user()
except spotipy.exceptions.SpotifyException:
    # 若认证失效,删除缓存文件并重新触发授权
    import os
    if os.path.exists(".cache"):
        os.remove(".cache")
    # 重新初始化并获取用户信息
    oauth_object = spotipy.SpotifyOAuth(
        client_id=clientID,
        client_secret=clientSecret,
        redirect_uri=redirectURI,
        scope=required_scopes,
        cache_path=".cache"
    )
    spotifyObject = spotipy.Spotify(auth_manager=oauth_object)
    user = spotifyObject.current_user()

2. 处理移除应用后的重新授权

当你在Spotify账户中移除应用授权后,本地缓存的refresh_token会失效。上述代码中添加了异常捕获,自动删除缓存文件并重新触发浏览器授权流程,无需手动操作。

3. 验证Spotify应用权限

登录Spotify开发者后台,检查你的应用是否已添加以下权限(对应代码中的required_scopes):

  • user-read-currently-playing:读取当前播放状态
  • user-modify-playback-state:修改播放队列

若未添加,需手动勾选并保存应用设置。

4. 优化播放监控逻辑(避免认证失效报错)

在playing函数中添加异常处理,防止因token过期导致程序崩溃:

def playing():
    while(True):
        if(boolean==True):
            try:
                data = pd.DataFrame(spotifyObject.currently_playing())
                if data.empty:
                    sleep(5)
                    print("未检测到正在播放的歌曲")
                    continue
                restante = (data.loc['duration_ms', 'item']-data.loc['duration_ms', 'progress_ms'])/1000

                if restante < 10 and data.loc['id', 'is_playing'] == True:
                    sleep(restante - 4)
                    spotifyObject.add_to_queue(uri(buscar_cancion()), device_id=None)
                    print("cambiando musica")
                    sleep(15)
                else:
                   sleep(5)
                   print("escanenado a True")
            except spotipy.exceptions.SpotifyException as e:
                print(f"认证异常:{e},正在重新获取授权...")
                # 重新初始化认证
                import os
                if os.path.exists(".cache"):
                    os.remove(".cache")
                global spotifyObject
                oauth_object = spotipy.SpotifyOAuth(
                    client_id=clientID,
                    client_secret=clientSecret,
                    redirect_uri=redirectURI,
                    scope=required_scopes,
                    cache_path=".cache"
                )
                spotifyObject = spotipy.Spotify(auth_manager=oauth_object)
                sleep(5)
        else:
            sleep(2)
            print("escanenado a false"+str(boolean))

关键说明

  • 不再手动提取access_token,而是通过auth_manager让Spotipy自动处理token的获取、刷新与缓存。
  • 缓存文件.cache存储了授权信息,删除该文件可强制重新触发授权流程。
  • 必须添加对应权限,否则调用播放相关接口会返回403权限错误。

内容的提问来源于stack exchange,提问作者zeus cabanas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 15:25:19