Thursday 12 September 2019

Storing Spotify token in flask session using spotipy?

I may have a bad understanding of how the flask session works, but I am trying to generate a Spotify API access token using SpotiPY with the Authorization Code Flow, and store it in Flask's session storage.

The program doesn't seem to be able to store it, and therefore later runs in to an error when trying to call it. Here is a visual explanation with images and captions: https://imgur.com/a/KiYZFiQ

Here is the main server script:

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)

and here are the two html files: Index.html, Results.html

Some things worth noting:

  • Credentz stores all of the private info including SSK, CLI_SEC, and CLI_ID.

  • The spotipy request works fine if I do it in a non-flask environment with no web-browser interaction.

  • I am able to store other things in the session storage, and call it back later, just not the access token for some reason.

  • My best guess is that the page doesn't have time to store it before the Spotify api redirects the page, not sure though.

Any help is really appreciated, Thank You!



from Storing Spotify token in flask session using spotipy?

No comments:

Post a Comment