使用Spotipy创建Spotify播放列表时遇无效用户名错误求助
解决Spotipy创建播放列表时的“无效用户名”错误
问题分析
切换到playlist-modify-public权限后调用user_playlist_create出现“Invalid username”错误,核心原因是Spotify API已不再支持使用显示用户名调用该接口,必须使用用户的唯一ID,或利用授权上下文省略用户参数。
解决方案
方案1:通过授权用户信息获取唯一ID调用
利用sp.me()方法获取当前授权用户的唯一ID,替换原代码中的显示用户名:
import spotipy import cred scope = 'playlist-modify-public' token = spotipy.util.prompt_for_user_token(cred.user_name, scope, client_id=cred.client_id, client_secret=cred.client_secret, redirect_uri=cred.redirect_url) sp = spotipy.Spotify(auth=token) # 获取当前授权用户的唯一ID current_user_id = sp.me()['id'] playlist_name = 'Test' sp.user_playlist_create(current_user_id, name=playlist_name)
方案2:省略用户参数(推荐)
Spotipy 2.x版本支持省略user参数,默认使用当前已授权的用户创建播放列表,简化代码:
import spotipy import cred scope = 'playlist-modify-public' token = spotipy.util.prompt_for_user_token(cred.user_name, scope, client_id=cred.client_id, client_secret=cred.client_secret, redirect_uri=cred.redirect_url) sp = spotipy.Spotify(auth=token) playlist_name = 'Test' # 省略用户参数,默认使用当前授权用户 sp.user_playlist_create(name=playlist_name)
额外检查项
- 确认
cred.user_name如果用于获取token,是否是正确的用户ID或Spotify登录邮箱(部分场景下显示用户名无法用于token获取) - 验证Spotify开发者后台配置的
redirect_uri和代码中完全一致,包括末尾的斜杠等细节 - 若仍有问题,清除本地缓存的token后重新授权,确保权限
playlist-modify-public已正确获取
内容的提问来源于stack exchange,提问作者Jakob S
相关产品推荐
相关产品推荐

