使用spotipy在flask会话中存储Spotify令牌?

2024-04-20 09:35:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我可能对flask会话的工作方式没有很好的理解,但是我试图使用SpotiPY和授权代码流生成一个Spotify API访问令牌,并将其存储在flask的会话存储中。在

程序似乎无法存储它,因此稍后在尝试调用它时遇到错误。下面是一个带有图片和标题的视觉说明:https://imgur.com/a/KiYZFiQ

以下是主服务器脚本:

from flask import Flask, render_template, redirect, request, session, make_response,session,redirect
import spotipy
import spotipy.util as util
from credentz import *
app = Flask(__name__)

app.secret_key = SSK

@app.route("/")
def verify():
    session.clear()
    session['toke'] = util.prompt_for_user_token("", scope='playlist-modify-private,playlist-modify-public,user-top-read', client_id=CLI_ID, client_secret=CLI_SEC, redirect_uri="http://127.0.0.1:5000/index")
    return redirect("/index")

@app.route("/index")
def index():
    return render_template("index.html")


@app.route("/go", methods=['POST'])
def go():
    data=request.form
    sp = spotipy.Spotify(auth=session['toke'])
    response = sp.current_user_top_artists(limit=data['num_tracks'], time_range=data['time_range'])
    return render_template("results.html",data=data)


if __name__ == "__main__":
    app.run(debug=True)

这是两个html文件:Index.htmlResults.html

值得注意的是:

  • Credentz存储所有私有信息,包括SSKCLI_SEC和{}。

  • 如果在没有web浏览器交互的非烧瓶环境中,spotipy请求可以正常工作。

  • 我可以在会话存储中存储其他内容,稍后再调用它,只是出于某种原因不能使用访问令牌。

  • 我最好的猜测是,在spotifyapi重定向页面之前,页面没有时间存储它,但不确定。

非常感谢您的帮助,谢谢!在


Tags: importappflaskdataindexsessiondefhtml
1条回答
网友
1楼 · 发布于 2024-04-20 09:35:38

您是对的,spotify在添加令牌之前会重定向您,从而结束该函数的执行。因此,您需要在重定向后添加一个回调步骤来获取身份验证令牌。在

斯波蒂的util.prompt_for_user_令牌方法不是为在web服务器中使用而设计的,所以最好的方法是自行实现身份验证流,然后在获得令牌后使用spotipy。幸运的是,spotify授权流非常简单,易于实现。在

方法一:自我实现授权流程:

from flask import Flask, render_template, redirect, request, session, make_response,session,redirect
import spotipy
import spotipy.util as util
from credentz import *
import requests
app = Flask(__name__)

app.secret_key = SSK

API_BASE = 'https://accounts.spotify.com'

# Make sure you add this to Redirect URIs in the setting of the application dashboard
REDIRECT_URI = "http://127.0.0.1:5000/api_callback"

SCOPE = 'playlist-modify-private,playlist-modify-public,user-top-read'

# Set this to True for testing but you probably want it set to False in production.
SHOW_DIALOG = True

# authorization-code-flow Step 1. Have your application request authorization; 
# the user logs in and authorizes access
@app.route("/")
def verify():
    auth_url = f'{API_BASE}/authorize?client_id={CLI_ID}&response_type=code&redirect_uri={REDIRECT_URI}&scope={SCOPE}&show_dialog={SHOW_DIALOG}'
    print(auth_url)
    return redirect(auth_url)

@app.route("/index")
def index():
    return render_template("index.html")

# authorization-code-flow Step 2.
# Have your application request refresh and access tokens;
# Spotify returns access and refresh tokens
@app.route("/api_callback")
def api_callback():
    session.clear()
    code = request.args.get('code')

    auth_token_url = f"{API_BASE}/api/token"
    res = requests.post(auth_token_url, data={
        "grant_type":"authorization_code",
        "code":code,
        "redirect_uri":"http://127.0.0.1:5000/api_callback",
        "client_id":CLI_ID,
        "client_secret":CLI_SEC
        })

    res_body = res.json()
    print(res.json())
    session["toke"] = res_body.get("access_token")

    return redirect("index")


# authorization-code-flow Step 3.
# Use the access token to access the Spotify Web API;
# Spotify returns requested data
@app.route("/go", methods=['POST'])
def go():
    data = request.form    
    sp = spotipy.Spotify(auth=session['toke'])
    response = sp.current_user_top_artists(limit=data['num_tracks'], time_range=data['time_range'])
    return render_template("results.html", data=data)

if __name__ == "__main__":
    app.run(debug=True)

另一方面,我们可以稍微作弊,使用spotipy本身使用的方法来节省一些代码。在

方法2:使用spotipy.oauth2.SpotifyOAuth方法:

^{pr2}$

在我看来,这两种方法都是同样有效的,只要你觉得哪个方法更容易理解就行了。在

确保在spotify应用程序仪表板中更新授权的重定向uri。在

有关更多信息,请参阅spotify文档:https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow

相关问题 更多 >