我创建了一个小应用程序。它的一部分显示用户的播放列表列表,供他们选择。首先,我遇到了用户无法再次登录的问题,因为我的 git 存储库中有一个缓存文件夹正在推送旧令牌。我删除了该缓存文件以及 pycache 文件夹。从那时起,当用户进入该页面选择他们的播放列表之一时,它会显示我的个人 Spotify 播放列表,而不是他们的!我不知道发生了什么事!我没有更改 app.py 文件中的任何代码。大约一个小时前,当用户第一次登录时,它会显示他们的播放列表。直到我删除了缓存文件。有关可能出现问题的任何线索吗?
这是相关页面的代码。 /toptracks 是重定向到 /selectedplaylist 页面的重定向 uri。这是登录用户的播放列表列表应显示为列表的位置。相反,我的播放列表正在显示...
app= Flask(__name__, template_folder='templates')
app.secret_key= appKey
app.config['SESSION_COOKIE_NAME']= 'A Cookie'
TOKEN_INFO= 'token_info'
def create_spotify_oauth():
return SpotifyOAuth(
client_id= SPOTIPY_CLIENT_ID,
client_secret= SPOTIPY_CLIENT_SECRET,
redirect_uri='https://myurl.com/toptracks',
scope= 'user-top-read'
)
@app.route("/")
def index():
sp_oauth= create_spotify_oauth()
auth_url= sp_oauth.get_authorize_url()
return render_template('index.html', auth_url=auth_url)
@app.route('/toptracks')
def redirector():
sp_oauth= create_spotify_oauth()
session.clear()
code= request.args.get('code')
token_info= sp_oauth.get_access_token(code)
print(token_info)
session[TOKEN_INFO]= token_info
return redirect('/selectplaylist')
@app.route('/selectplaylist')
def selectPlaylist():
try:
token_info= get_token()
except:
print('try logging in again')
redirect('/')
sp= spotipy.Spotify(auth=token_info['access_token'])
user= sp.current_user()['id']
allPlaylists= sp.user_playlists(user=user,limit=50)['items']
playName= [[i.get('name'),i.get('id')] for i in allPlaylists]
playId= [i.get('id') for i in allPlaylists]
return render_template('selectPlaylist.html',playName=playName,playId=playId)
def get_token():
token_info= session.get(TOKEN_INFO, None)
if not token_info:
raise 'exception'
now = int(time.time())
is_expired= token_info['expires_at'] - now < 60
if (is_expired):
sp_oauth= create_spotify_oauth()
token_info= sp_oauth.refresh_access_token(token_info['refresh_token'])
return token_info
我尝试删除其他一些缓存文件,但这并没有解决任何问题。我不确定我还可以尝试什么,因为代码本身似乎很好。我对自己可以尝试什么感到困惑,因为几个小时前它还运行得很好。
对我来说,这个问题是由 Spotify 在我的系统中自动创建 .cache 文件引起的。每当拉出 Spotify 用户数据时,我都在我的模块中应用了这个 cleanup() 函数,它修复了所有问题:
def cleanup():
cache_file = '.cache'
if os.path.exists(cache_file):
os.remove(cache_file)