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)
我可以使用我的 Spotify 帐户登录,但在同意连接时遇到“访问本地主机被拒绝您无权查看此页面。 HTTP 错误 403"
尝试创建新应用程序,更改浏览器(从 chrome 到 safari),清除 cookie。我还使用了不带spotipy的spotify的api并且它有效(艺术家的前10首曲目),如果这个信息有任何帮助的话。
Spotipy 是 Spotify Web API 的 Python 库,通过抽象化管理身份验证流程、令牌和令牌刷新所涉及的大部分复杂性,简化了 OAuth2 身份验证的处理。
Spotipy 的内置 OAuth 流程减少了手动回调处理和代码解码的需求,这通常在其他环境中出现,例如将 Express 与 Node.js 结合使用:
demo.py
import spotipy
from flask import Flask, redirect, session, url_for
from spotipy.oauth2 import SpotifyOAuth
from spotipy import cache_handler
import os
app = Flask(__name__)
# Set your Spotify API credentials as environment variables, it will pick by spotipy API
client_id = os.getenv("CLIENT_ID")
if client_id is not None:
os.environ["SPOTIPY_CLIENT_ID"] = client_id
else:
print("CLIENT_ID environment variable is not set.")
client_secret = os.getenv("CLIENT_SECRET")
if client_secret is not None:
os.environ["SPOTIPY_CLIENT_SECRET"] = client_secret
else:
print("CLIENT_SECRET environment variable is not set.")
# Set your redirect URI
os.environ["SPOTIPY_REDIRECT_URI"] = "http://localhost:3000/callback"
# Define the required OAuth scope
oAuthscope = "playlist-read-private"
# Initialize the cache handler and auth manager for Spotipy
Sp_Cache = cache_handler.CacheFileHandler()
auth_manager = spotipy.SpotifyOAuth(scope=oAuthscope, cache_handler=Sp_Cache)
sp_oauth = spotipy.Spotify(auth_manager=auth_manager)
# Ensure the Flask application has a secret key for secure sessions
app.secret_key = os.urandom(24)
@app.route('/')
def home():
return redirect(url_for('get_playlists'))
@app.route('/get_playlists')
def get_playlists():
playlists = sp_oauth.current_user_playlists()
playlists_info = [(pl['name'], pl['external_urls']['spotify']) for pl in playlists['items']]
playlists_html = '<br>'.join([f'{name}: {url}' for name, url in playlists_info])
return playlists_html
@app.route('/logout')
def logout():
# Clearing the Flask session for logging out
session.clear()
return redirect(url_for('home'))
# run flask app when file is run
if __name__ == '__main__':
app.run(debug=True)