You need to enable JavaScript to run this app. 如何在Flask Web服务器中完成Spotipy的用户令牌身份验证?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask Web服务器中完成Spotipy的用户令牌身份验证?

当前代码的核心问题

你现在的写法完全没有打通Flask和Spotify OAuth的交互流程,直接导致认证逻辑无法正常跑通:

  • 全局直接实例化Spotify客户端的写法,会在服务启动时就触发授权校验,既无法处理Spotify重定向返回的授权码,也没有把授权状态和单个用户的会话绑定,调用播放控制接口时必然会抛出令牌缺失的错误。
  • 配置的重定向地址指向根路由,但根路由没有解析Spotify回调携带的授权码参数,授权流程走到重定向环节就会中断。
  • 默认的令牌本地文件缓存机制没有适配Flask的多请求运行模式,并发场景下会出现令牌错乱。
修正后的完整可运行代码
from flask import Flask, redirect, request, session, url_for
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from spotipy.cache_handler import FlaskSessionCacheHandler

app = Flask(__name__)
# 必须配置固定的SECRET_KEY才能正常使用Flask会话存储
app.secret_key = "替换为你自定义的随机固定字符串"

# 抽离公共的OAuth配置方法,不要全局实例化认证对象
def get_spotify_auth_manager():
    oauth = SpotifyOAuth(
        client_id="你的Spotify开发者平台Client ID",
        client_secret="你的Spotify开发者平台Client Secret",
        redirect_uri="http://localhost:5000/callback",
        scope="user-read-playback-state,user-modify-playback-state,user-read-currently-playing,app-remote-control"
    )
    # 用官方提供的会话缓存处理器,把令牌存在用户会话中
    cache_handler = FlaskSessionCacheHandler(session)
    oauth.cache_handler = cache_handler
    return oauth

@app.route("/")
def index():
    auth_manager = get_spotify_auth_manager()
    # 校验当前用户的会话是否有有效令牌
    token = auth_manager.cache_handler.get_cached_token()
    if not auth_manager.validate_token(token):
        # 没有有效令牌的话,直接重定向到Spotify官方授权页
        return redirect(auth_manager.get_authorize_url())
    # 授权通过后正常渲染仪表盘页面
    return render_template("index.html")

@app.route("/callback")
def spotify_auth_callback():
    auth_manager = get_spotify_auth_manager()
    # 从Spotify的回调请求中提取授权码,换取访问令牌
    auth_code = request.args.get("code")
    auth_manager.get_access_token(auth_code)
    # 令牌存好后跳回仪表盘首页
    return redirect(url_for("index"))

@app.route("/pause")
def pause_playback():
    auth_manager = get_spotify_auth_manager()
    # 操作前先校验令牌有效性,避免无效调用
    token = auth_manager.cache_handler.get_cached_token()
    if not auth_manager.validate_token(token):
        return redirect(url_for("index"))
    # 每次请求基于当前会话的令牌生成客户端实例
    sp = spotipy.Spotify(auth_manager=auth_manager)
    sp.pause_playback()
    return "播放暂停操作已触发"

if __name__ == "__main__":
    app.run(debug=True)
关键注意事项
  • 必须在Spotify开发者后台的应用设置中,把http://localhost:5000/callback添加到允许的重定向URI列表中,否则Spotify会直接拦截授权请求。
  • 不要全局实例化Spotify客户端或认证对象:每次请求基于当前用户会话的令牌生成对应实例,从根本上避免多用户、并发请求下的令牌冲突。
  • 不要用默认的本地文件做令牌缓存:用官方提供的FlaskSessionCacheHandler把令牌存在用户会话中,不需要额外维护本地缓存文件,令牌的自动刷新逻辑也会正常生效。
  • 部署上线时务必关闭debug=True,同时把app.secret_key替换为高复杂度的随机值,避免会话被伪造、服务信息泄露。
  • 采用会话存储令牌的模式下,每个访问仪表盘的用户都需要单独完成一次Spotify授权,才能控制自己账号下的播放状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 13:24:00