Spotipy Oauth2 流存储令牌
Posted
技术标签:
【中文标题】Spotipy Oauth2 流存储令牌【英文标题】:Spotipy Oauth2 Flow Storing Tokens 【发布时间】:2020-03-17 20:18:51 【问题描述】:我正在尝试为我使用 spotipy 制作的 spotify 应用程序实现 oauth2。我可能对 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 *
import time
import json
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://localhost:8080"
SCOPE = 'playlist-modify-private,playlist-modify-public,user-top-read'
# Set this to True for testing but you probaly 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():
# Don't reuse a SpotifyOAuth object because they store token info and you could leak user tokens if you reuse a SpotifyOAuth object
sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id = CLI_ID, client_secret = CLI_SEC, redirect_uri = REDIRECT_URI, scope = SCOPE)
auth_url = sp_oauth.get_authorize_url()
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():
# Don't reuse a SpotifyOAuth object because they store token info and you could leak user tokens if you reuse a SpotifyOAuth object
sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id = CLI_ID, client_secret = CLI_SEC, redirect_uri = REDIRECT_URI, scope = SCOPE)
session.clear()
code = request.args.get('code')
token_info = sp_oauth.get_access_token(code)
# Saving the access token along with all other token related info
session["token_info"] = token_info
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():
session['token_info'], authorized = get_token(session)
session.modified = True
if not authorized:
return redirect('/')
data = request.form
sp = spotipy.Spotify(auth=session.get('token_info').get('access_token'))
response = sp.current_user_top_tracks(limit=data['num_tracks'], time_range=data['time_range'])
# print(json.dumps(response))
return render_template("results.html", data=data)
# Checks to see if token is valid and gets a new token if not
def get_token(session):
token_valid = False
token_info = session.get("token_info", )
# Checking if the session already has a token stored
if not (session.get('token_info', False)):
token_valid = False
return token_info, token_valid
# Checking if token has expired
now = int(time.time())
is_token_expired = session.get('token_info').get('expires_at') - now < 60
# Refreshing token if it has expired
if (is_token_expired):
# Don't reuse a SpotifyOAuth object because they store token info and you could leak user tokens if you reuse a SpotifyOAuth object
sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id = CLI_ID, client_secret = CLI_SEC, redirect_uri = REDIRECT_URI, scope = SCOPE)
token_info = sp_oauth.refresh_access_token(session.get('token_info').get('refresh_token'))
token_valid = True
return token_info, token_valid
if __name__ == "__main__":
app.run(debug=True)
我在网站的其他地方找到了这段代码。但是,模块“credentz”似乎不存在。任何人都知道如何在 spotipy 中存储多个 spotify 帐户的令牌?
【问题讨论】:
我已经编写了一个 example 身份验证服务器,它使用我自己的 Web API 包装器 Tekore 来完成此任务。也许它对你有帮助。它有点类似于 Spotipy,所以也许你可以根据自己的需要调整它。 【参考方案1】:spotipy 存储库https://github.com/plamere/spotipy/blob/master/examples/app.py 中添加了一个示例 Flask API 应用程序
【讨论】:
以上是关于Spotipy Oauth2 流存储令牌的主要内容,如果未能解决你的问题,请参考以下文章
在 Oauth2 隐式授权流和第 3 方 cookie 中刷新令牌