我试图允许用户使用Spotify登录(使用Spotipy库),为在他们的帐户上创建播放列表和填充播放列表提供身份验证。在用户登录后,我将通过一个嵌入式Spotify播放器(使用新创建的播放列表的播放列表ID )在重定向模板中显示他们刚刚创建的播放列表。
我的HTML模板中有一个表单输入框,它接受用户的输入(他们的Spotify用户名)。我还有一个Spotify URI列表,用于播放列表中的曲目。
我遵循了Spotipy文档关于为用户获取用于身份验证的令牌,如下所示(我已经删除了我的客户端id和秘密)。我不知道为什么不起作用:
import os
import spotipy
import spotipy.util as util
from json.decoder import JSONDecodeError
from datetime import date
@login_required
def save_playlist(request, data='Default_Data'):
username = data.split('/')[0] #spotify username
track_ids = data.split('/')[1:11] #list of spotify IDs for playlist tracks
client_id = '****'
client_secret = '****'
scope = 'playlist-modify-public, playlist-modify-private'
redirect_uri = 'http://127.0.0.1:8000/save_playlist/'
#check if username is already in cache, if not, create cache
try:
token = util.prompt_for_user_token(username,
scope=scope,client_id=client_id,
client_secret=client_secret,redirect_uri=redirect_uri)
except (AttributeError, JSONDecodeError):
os.remove(f".cache-{username}")
token = util.prompt_for_user_token(username,
scope=scope,client_id=client_id,
client_secret=client_secret,redirect_uri=redirect_uri)
sp=spotipy.Spotify(auth=token)
today = date.today()
date_string = (str(today.day) + ' - ' + str(today.month) + ' - ' + str(today.year))
#playlist title
playlist_name = f"GENIE - " + username + ' | ' + date_string
#create a new public playlist to be populated
sp.user_playlist_create(username, name=playlist_name, public=True)
#id of playlist we just created
playlist_id = sp.current_user_playlists(limit=1)['items'][0]['id']
#add playlist tracks to this playlist
sp.user_playlist_add_tracks(username,playlist_id,tracks=track_ids)
return render(request, 'blog/save_playlist.html', {'playlist_id':playlist_id})当用户向Spotify输入用户名和登录时,多个窗口不断弹出,而不仅仅是一个窗口(参见下面的终端)。我相信问题在某种程度上是在获得令牌。
尝试登录时终端输出

我已经将Spotify开发人员控制台中的重定向URI设置为与上面的相同('播放列表/')。
提前感谢!
发布于 2021-01-10 12:46:22
util.prompt_for_user_token不应该在允许任何用户登录的web应用程序中使用,因为我们事先不知道用户的ID/名称。它只是一个在本地快速启动的助手。
相反,您应该直接使用spotipy.oauth2.SpotifyOAuth,为用户指定唯一的缓存路径。在web应用程序的情况下,它将是一个会话ID。
下面是一个为水瓶制作的完整示例,您可以适应您的需要,https://github.com/plamere/spotipy/blob/master/examples/app.py
发布于 2022-05-29 11:47:26
尝试一下OAuth请求-oauthlib https://requests-oauthlib.readthedocs.io/en/latest/examples/spotify.html,它的工作原理就像一种魅力。
发布于 2020-03-26 02:11:02
与使用Spotipy不同,一个快速的解决方案是转到https://pypi.org/project/spotify-token/,它是一个Python脚本,如果提供Spotify用户名和密码,它可以生成Spotify令牌。
尽管如此,请记住,并不是每个人都会自愿提供用户名和密码。干杯!
https://stackoverflow.com/questions/60838288
复制相似问题