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

Spotify API异常:用户页面显示我的个人播放列表求助

问题

开发了一款小型Flask应用,核心功能是展示登录用户的Spotify播放列表供选择。此前因Git仓库中的缓存文件夹存在旧令牌,导致用户无法重新登录,删除该缓存文件及__pycache__文件夹后,出现新问题:用户进入播放列表选择页面时,显示的是开发者个人的Spotify播放列表,而非用户自身的!未修改app.py代码,数小时前功能还正常,尝试删除其他缓存文件无效,附上相关代码请求排查原因。

相关代码:

app= Flask(__name__, template_folder='templates')
app.secret_key= appKey
app.config['SESSION_COOKIE_NAME']= 'A Cookie'
TOKEN_INFO= 'token_info'

def create_spotify_oauth():
    return SpotifyOAuth(
         client_id= SPOTIPY_CLIENT_ID,
         client_secret= SPOTIPY_CLIENT_SECRET,
         redirect_uri='https://myurl.com/toptracks',
         scope= 'user-top-read'
    )

@app.route("/")
def index():
    sp_oauth= create_spotify_oauth()
    auth_url= sp_oauth.get_authorize_url()
    return render_template('index.html', auth_url=auth_url)

@app.route('/toptracks')
def redirector():
    sp_oauth= create_spotify_oauth()
    session.clear()
    code= request.args.get('code')
    token_info= sp_oauth.get_access_token(code)
    print(token_info)
    session[TOKEN_INFO]= token_info
    return redirect('/selectplaylist')

@app.route('/selectplaylist')
def selectPlaylist():
    try:
        token_info= get_token()
    except:
        print('try logging in again')
        redirect('/')
    sp= spotipy.Spotify(auth=token_info['access_token'])
    user= sp.current_user()['id']
    allPlaylists= sp.user_playlists(user=user,limit=50)['items']
    playName= [[i.get('name'),i.get('id')] for i in allPlaylists]
    playId= [i.get('id') for i in allPlaylists]
    return render_template('selectPlaylist.html',playName=playName,playId=playId)

def get_token():
    token_info= session.get(TOKEN_INFO, None)
    if not token_info:
        raise 'exception'
    now = int(time.time())
    is_expired= token_info['expires_at'] - now < 60
    if (is_expired):
        sp_oauth= create_spotify_oauth()
        token_info= sp_oauth.refresh_access_token(token_info['refresh_token'])
    return token_info

排查与解决思路

  • SpotifyOAuth本地缓存残留:Spotipy的SpotifyOAuth默认会生成本地缓存文件(如.cache开头的文件),即使删除了Git仓库中的缓存,服务器运行目录下可能还存在旧缓存,复用了开发者的个人令牌。需显式禁用本地文件缓存,完全依赖Flask Session存储令牌。
  • Flask Session跳转逻辑缺陷:selectPlaylist函数中捕获异常后,redirect('/')未加return,导致异常后仍会执行后续代码,可能使用旧令牌。需添加return确保跳转生效。
  • 令牌刷新后未更新Session:get_token函数刷新令牌后,未将新令牌存入Session,导致后续请求复用旧令牌。需将刷新后的令牌重新写入Session。

关键代码修正

1. 禁用SpotifyOAuth本地缓存

def create_spotify_oauth():
    return SpotifyOAuth(
         client_id= SPOTIPY_CLIENT_ID,
         client_secret= SPOTIPY_CLIENT_SECRET,
         redirect_uri='https://myurl.com/toptracks',
         scope= 'user-top-read',
         cache_path=None  # 禁用本地文件缓存,完全依赖Session存储
    )

2. 修复播放列表页面的异常跳转

@app.route('/selectplaylist')
def selectPlaylist():
    try:
        token_info= get_token()
    except:
        print('try logging in again')
        return redirect('/')  # 添加return,确保异常时跳转到登录页
    sp= spotipy.Spotify(auth=token_info['access_token'])
    user= sp.current_user()['id']
    allPlaylists= sp.user_playlists(user=user,limit=50)['items']
    playName= [[i.get('name'),i.get('id')] for i in allPlaylists]
    playId= [i.get('id') for i in allPlaylists]
    return render_template('selectPlaylist.html',playName=playName,playId=playId)

3. 令牌刷新后更新Session

def get_token():
    token_info= session.get(TOKEN_INFO, None)
    if not token_info:
        raise 'exception'
    now = int(time.time())
    is_expired= token_info['expires_at'] - now < 60
    if (is_expired):
        sp_oauth= create_spotify_oauth()
        token_info= sp_oauth.refresh_access_token(token_info['refresh_token'])
        session[TOKEN_INFO] = token_info  # 将刷新后的令牌存入Session
    return token_info

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:03:15