type hereimport os
import spotipy
from flask import Flask, session, redirect, url_for,request
from dotenv import load_dotenv
from spotipy import Spotify
from spotipy.oauth2 import SpotifyOAuth
from spotipy.cache_handler import FlaskSessionCacheHandler
load_dotenv()
# creates flask app and stores it in variable
app = Flask(__name__)
# can make a permanent key later
app.config['SECRET_KEY'] = os.urandom(64)
client_id = os.getenv("CLIENT_ID")
client_secret = os.getenv("CLIENT_SECRET")
redirect_uri = "http://localhost:5000/callback"
# mention scopes of the project
scope = 'playlist-read-private'
# allow spotipy to store access token in flask session
cache_handler = FlaskSessionCacheHandler(session)
# authentication manager
sp_oauth = SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope,
cache_handler= cache_handler,
show_dialog = True
)
# create instance of spotify client, call methods using up to get data
sp = Spotify(auth_manager=sp_oauth)
# end point
@app.route('/')
def home():
# check if logged in already or not
# sp_ouath method validate_token checks if we have a valid token
# while get_cached_token method returns token from flask session
if not sp_oauth.validate_token(cache_handler.get_cached_token()):
# if we don't then ask for login/token
auth_url = sp_oauth.get_authorize_url()
return redirect(auth_url)
return redirect(url_for('get_playlists'))
# refreshes token on behalf of user
@app.route('/callback')
def callback():
sp_oauth.get_access_token(request.args['code'])
return redirect(url_for('get_playlists'))
@app.route('/get_playlists')
def get_playlists():
# check if token is valid just incase
if not sp_oauth.validate_token(cache_handler.get_cached_token()):
auth_url = sp_oauth.get_authorize_url()
return redirect(auth_url)
playlists = sp.current_user_playlists()
playlists_info = [(pl['name'], pl['external_url']['spotify']) for pl in playlists['items']]
playlists_html = '<br>'.join([f'{name}: {url}' for name, url in playlists_info])
return playlists_html
# log out
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('home'))
# run flask app when file is run
if __name__ == '__main__':
app.run(debug=True)
I’m able to login with my spotify account but when agreeing to connect I’m encountering ” Access to localhost was deniedYou don’t have authorization to view this page.
HTTP ERROR 403″
Tried Creating new app, changed browser (from chrome to safari), cleared cookies. I also used spotify’s api without spotipy and it worked (top 10 tracks of an artist), if this info helps in any way.