Flask开发Spotify应用:获取终端用户数据异常问题排查
问题根源
你遇到的核心问题是SpotifyOAuth默认使用本地文件缓存(.cache),所有访问应用的用户共享同一个缓存文件。一旦你用自己的账号完成第一次授权,后续所有请求都会复用这个缓存里的token,自然只会返回你的数据。
解决方案
要让每个用户的授权数据独立,需要给每个用户分配专属的缓存空间,或者完全绕过Spotify的缓存机制,直接用Flask Session存储token。
方案1:为每个用户配置独立内存缓存
修改你的create_spotify_oauth函数,使用MemoryCacheHandler并基于Flask Session的唯一ID作为缓存键,确保每个用户的token互不干扰:
from spotipy.cache_handler import MemoryCacheHandler def create_spotify_oauth(): # 用Session的唯一标识作为缓存键,隔离不同用户的授权数据 cache_handler = MemoryCacheHandler(cache_key=session.sid) return SpotifyOAuth( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=url_for('redirectPage', _external=True), scope='playlist-modify-public', cache_handler=cache_handler, # 强制每次授权显示账号选择界面,避免浏览器自动登录你的账号 show_dialog=True )
方案2:完全依赖Flask Session存储Token
跳过Spotify的缓存机制,直接将获取到的token存入Session,后续调用API时从Session取出初始化客户端:
# 修改redirectPage路由,确保token正确存入Session @app.route('/redirectPage') def redirectPage(): sp_oauth = create_spotify_oauth() code = request.args.get('code') # 传入check_cache=False,避免读取全局缓存 token_info = sp_oauth.get_access_token(code, check_cache=False) session[TOKEN_INFO] = token_info return redirect(url_for('playlist_or_album')) # 在业务路由中直接用Session里的token初始化Spotify客户端 @app.route('/playlist_or_album') def playlist_or_album(): token_info = session.get(TOKEN_INFO) if not token_info: return redirect(url_for('authentication')) # 直接使用Session中的token创建客户端,绕过缓存 sp = spotipy.Spotify(auth=token_info['access_token']) # 这里获取的就是当前终端用户的数据 user_data = sp.current_user() return f"当前用户:{user_data['display_name']}" # 对应的create_spotify_oauth可以简化(不需要缓存配置) def create_spotify_oauth(): return SpotifyOAuth( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=url_for('redirectPage', _external=True), scope='playlist-modify-public', show_dialog=True )
关键注意事项
- 确保你的Flask应用已设置
SECRET_KEY(比如app.secret_key = 'your_secret_key_here'),否则Session无法正常存储数据 - 测试时使用浏览器隐私窗口,或者清除原有授权Cookie,避免浏览器自动登录你的账号
- 不要在
SpotifyOAuth中设置username参数,这个参数会强制绑定到指定用户,导致授权流程跳过账号选择
内容的提问来源于stack exchange,提问作者thetaco
相关产品推荐
相关产品推荐

