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

使用Spotipy访问用户播放列表时遭遇localhost HTTP 403权限拒绝错误

问题描述

使用Spotipy结合Flask开发应用时,可正常登录Spotify账号,但同意授权后出现Access to localhost was deniedYou don't have authorization to view this page. HTTP ERROR 403错误。已尝试创建新应用、更换浏览器、清除Cookie,且直接调用Spotify API获取艺术家Top10曲目功能正常,寻求解决方案。

相关代码

import os
import spotipy
from flask import Flask, session, redirect, url_for,request
from dotenv import load_dotenv

from spotipy import Spotify
from spotipy.oauth2 import SpotifyOAuth
from spotipy.cache_handler import FlaskSessionCacheHandler

load_dotenv()

# creates flask app and stores it in variable
app = Flask(__name__)
# can make a permanent key later
app.config['SECRET_KEY'] = os.urandom(64)
client_id = os.getenv("CLIENT_ID")
client_secret = os.getenv("CLIENT_SECRET")

redirect_uri = "http://localhost:5000/callback"

# mention scopes of the project
scope = 'playlist-read-private'

# allow spotipy to store access token in flask session
cache_handler = FlaskSessionCacheHandler(session)
# authentication manager
sp_oauth = SpotifyOAuth(
    client_id=client_id,
    client_secret=client_secret,
    redirect_uri=redirect_uri,
    scope=scope,
    cache_handler= cache_handler,
    show_dialog = True
)

# create instance of spotify client, call methods using up to get data
sp = Spotify(auth_manager=sp_oauth)

# end point
@app.route('/')
def home():
    # check if logged in already or not
    # sp_ouath method validate_token checks if we have a valid token
    # while get_cached_token method returns token  from flask session

    if not sp_oauth.validate_token(cache_handler.get_cached_token()):
        # if we don't then ask for login/token
        auth_url = sp_oauth.get_authorize_url()
        return redirect(auth_url)
    return redirect(url_for('get_playlists'))

# refreshes token on behalf of user
@app.route('/callback')
def callback():
    sp_oauth.get_access_token(request.args['code'])
    return redirect(url_for('get_playlists'))


@app.route('/get_playlists')
def get_playlists():
    # check if token is valid just incase
    if not sp_oauth.validate_token(cache_handler.get_cached_token()):
        auth_url = sp_oauth.get_authorize_url()
        return redirect(auth_url)

    playlists = sp.current_user_playlists()
    playlists_info = [(pl['name'], pl['external_url']['spotify']) for pl in playlists['items']]
    playlists_html = '<br>'.join([f'{name}: {url}' for name, url in playlists_info])

    return playlists_html

# log out
@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('home'))

# run flask app when file is run
if __name__ == '__main__':
    app.run(debug=True)
解决方案

1. 修正API字段调用错误

代码中get_playlists函数里的pl['external_url']['spotify']是错误的,Spotify API返回的字段为**external_urls**(复数形式),该错误会导致授权后抛出异常,间接引发403错误。修改为:

playlists_info = [(pl['name'], pl['external_urls']['spotify']) for pl in playlists['items']]

2. 验证Spotify开发者后台重定向URI匹配度

登录Spotify开发者后台,进入目标应用的Settings页面:

  • 在Redirect URIs区域,确认添加的URI与代码中redirect_uri完全一致,包括协议、端口和路径(即http://localhost:5000/callback)
  • 修改后点击Save保存配置

3. 固定Flask的SECRET_KEY

os.urandom(64)会在应用每次重启时生成随机密钥,导致Flask Session失效,引发授权后验证异常。改为固定密钥:

app.config['SECRET_KEY'] = "your_custom_fixed_secret_key"  # 替换为自定义固定字符串

4. 完善回调函数的错误处理

当前callback函数未处理获取Token失败的情况,添加异常捕获避免无提示跳转错误:

@app.route('/callback')
def callback():
    try:
        sp_oauth.get_access_token(request.args['code'])
    except Exception as e:
        return f"Token获取失败: {str(e)}"
    return redirect(url_for('get_playlists'))

5. 关闭Flask Debug模式(可选)

Debug模式下Flask会自动重启两次,可能导致Session状态紊乱。若以上步骤无效,尝试关闭Debug模式:

if __name__ == '__main__':
    app.run(debug=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:47:03