如何在单个SpotifyOAuth对象中配置多个Scope解决权限不足问题?
问题:单个Spotify令牌配置多个权限范围失败
我想给单个Spotify令牌配置多个权限范围(Scope),一次授权就能使用所有权限。我写了如下Spotify类,在初始化时创建SpotifyOAuth相关对象:
class Spotify(): """Spotify class that contains plenty of methods to handle your user or retrieve data""" def __init__(self, cid, secret) -> None: self.cid = cid self.Secret = secret scope = 'user-read-private user-read-recently-played' # Get the token so we don't need to access every time token = util.prompt_for_user_token(scope, client_id=self.cid, client_secret=self.Secret) sp = spotipy.Spotify(auth=token) self.Username, self.followers, self.id = try_to_login(sp) self.sp = sp
其中user-read-private权限可以正常使用,但调用self.sp.current_user_recently_played(limit=50)时出现403权限不足错误:
return self._get( File "C:\Users\kyria\AppData\Roaming\Python\Python39\site-packages\spotipy\client.py", line 321, in _get return self._internal_call("GET", url, payload, kwargs) File "C:\Users\kyria\AppData\Roaming\Python\Python39\site-packages\spotipy\client.py", line 291, in _internal_call raise SpotifyException( spotipy.exceptions.SpotifyException: http status: 403, code:-1 - https://api.spotify.com/v1/me/player/recently-played?limit=50: Insufficient client scope, reason: None
我试过三种Scope定义方式:空格分隔(如上代码)、逗号分隔scope = 'user-read-private,user-read-recently-played'、列表形式scope = ['user-read-private', 'user-read-recently-played'],都没解决问题。请问怎么让单个SpotifyOAuth对象使用多个Scope?
解决方案
问题根源是Spotipy会缓存已授权的令牌,你之前可能只用user-read-private授权过,缓存的旧令牌没有包含新添加的user-read-recently-played权限,所以即使修改了scope参数,程序还是在使用旧缓存的令牌。
解决步骤:
- 删除旧缓存文件:Spotipy默认的缓存文件是项目目录下的
.cache-<你的Spotify用户名>文件,直接删除它,重新运行程序会触发新的授权流程,新令牌会包含所有指定的scope。 - 指定新的缓存路径:如果不想删除旧缓存,可以在调用
prompt_for_user_token时添加cache_path参数,设置新的文件路径强制生成新令牌:token = util.prompt_for_user_token( scope, client_id=self.cid, client_secret=self.Secret, cache_path=".cache-new-token" # 自定义新缓存文件路径 ) - 确认scope写法:空格分隔多个scope是Spotify官方推荐格式,列表形式Spotipy也会自动转换为正确格式,你的写法本身没有问题,核心问题出在缓存。
修正后重新授权,新令牌会包含所有指定的权限范围,调用current_user_recently_played就不会再出现权限不足的错误。
内容的提问来源于stack exchange,提问作者Kiriakospapa
相关产品推荐
相关产品推荐

