Fix Flask example app (#539)

This commit is contained in:
Stéphane Bruckert 2020-07-26 20:46:35 +01:00 committed by GitHub
parent 36bbf7d15e
commit f136442c2d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,9 +3,11 @@ Prerequisites
pip3 install spotipy Flask Flask-Session
// from your [app settings](https://developer.spotify.com/dashboard/applications)
export SPOTIPY_CLIENT_ID=client_id_here
export SPOTIPY_CLIENT_SECRET=client_secret_here
export SPOTIPY_REDIRECT_URI='http://127.0.0.1:8080' // added to your [app settings](https://developer.spotify.com/dashboard/applications)
export SPOTIPY_REDIRECT_URI='http://127.0.0.1:8080' // must contain a port
// on Windows, use `SET` instead of `export`
Run app.py
@ -17,27 +19,38 @@ import os
from flask import Flask, session, request, redirect
from flask_session import Session
import spotipy
import uuid
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(64)
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_FILE_DIR'] = './.flask_session/'
Session(app)
auth_manager = spotipy.oauth2.SpotifyOAuth()
spotify = spotipy.Spotify(auth_manager=auth_manager)
caches_folder = './.spotify_caches/'
if not os.path.exists(caches_folder):
os.makedirs(caches_folder)
@app.route('/')
def index():
if not session.get('uuid'):
# Step 1. Visitor is unknown, give random ID
session['uuid'] = str(uuid.uuid4())
auth_manager = spotipy.oauth2.SpotifyOAuth(cache_path=session_cache_path(), show_dialog=True)
if request.args.get("code"):
session['token_info'] = auth_manager.get_access_token(request.args["code"])
# Step 3. Being redirected from Spotify auth page
auth_manager.get_access_token(request.args.get("code"))
return redirect('/')
if not session.get('token_info'):
if not auth_manager.get_cached_token():
# Step 2. Display sign in link when no token
auth_url = auth_manager.get_authorize_url()
return f'<h2><a href="{auth_url}">Sign in</a></h2>'
# Step 4. Signed in, display data
spotify = spotipy.Spotify(auth_manager=auth_manager)
return f'<h2>Hi {spotify.me()["display_name"]}, ' \
f'<small><a href="/sign_out">[sign out]<a/></small></h2>' \
f'<a href="/playlists">my playlists</a>'
@ -45,13 +58,21 @@ def index():
@app.route('/sign_out')
def sign_out():
os.remove(session_cache_path())
session.clear()
return redirect('/')
@app.route('/playlists')
def playlists():
if not session.get('token_info'):
auth_manager = spotipy.oauth2.SpotifyOAuth(cache_path=session_cache_path())
if not auth_manager.get_cached_token():
return redirect('/')
else:
spotify = spotipy.Spotify(auth_manager=auth_manager)
return spotify.current_user_playlists()
def session_cache_path():
return caches_folder + session.get('uuid')