如何在一个 SpotifyOAuth 对象中包含多个范围?

问题描述 投票:0回答:1

我试图将多个范围传递给一个令牌,以便必须输入我只被重定向一次的 URL。我创建了一个类

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)
时,我收到此错误:

 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

我尝试根据here定义范围,正如您在代码中看到的那样,也根据

official documentation
scope = 'user-read-private,user-read-recently-played'
scope = ['user-read-private', 'user-read-recently-played']的形式定义范围。

如果这 3 个都不起作用,我如何才能在一个 SpotifyOAuth 对象上使用多个范围?

python authorization spotify spotipy scopes
1个回答
0
投票

Spotify 上的 Get Recently Played Tracks API 专门处理与用户相关的数据。 您尝试访问的信息与用户帐户相关联,因此,必须获得用户授权才能访问他们最近播放的曲目。

你需要具备两个条件

#1 授权代码流 + #2
user-read-recently-played
范围

此图显示了与 Spotify 文档的不同之处。

授权代码流 vs. 客户端凭证流

403错误是一个

Insufficient client scope
错误。

我想你错过了任何一个,可能错过了范围或者没有用户登录所需的代码流步骤。

此 python 代码将使用

spotipy
v 2.22.1

另存为

get-songs.py

import spotipy
from spotipy.oauth2 import SpotifyOAuth
import os

# Set your Spotify API credentials as environment variables, it will pick by spotipy API
os.environ["SPOTIPY_CLIENT_ID"] = "<your client ID>"
os.environ["SPOTIPY_CLIENT_SECRET"] = "<your client Secret>"
os.environ["SPOTIPY_REDIRECT_URI"] = "<your App's registered redirect URI>"

# Just this scope good enough to get user_recently_played API
scope = "user-read-recently-played"

# This API call raise web browser and ask user login for getting callback with Authorization Code flow
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

# After get token, can call real API
recently_played = sp.current_user_recently_played()

# from the result, we picked up the songs track information
for idx, item in enumerate(recently_played["items"]):
    track = item["track"]
    print(idx, track['artists'][0]['name'], " – ", track['name'])

安装依赖

pip install spotipy os

运行它

python get-songs.py

用户登录步骤

结果

如果你想使用 Flaks & requests(低级别)而不是

spotipy
(高级别) 在这里

此客户端凭证流示例

© www.soinside.com 2019 - 2024. All rights reserved.