gpt4 book ai didi

python - spotipy授权代码流程

转载 作者:太空狗 更新时间:2023-10-29 22:26:11 25 4
gpt4 key购买 nike

我正在使用 Spotipy python 库与 Spotify web api 进行交互。我已经完成了 API 和文档,但我没有看到一个清晰的示例来说明该库如何支持授权代码流 (https://developer.spotify.com/web-api/authorization-guide/#authorization-code-flow)。

最佳答案

我在 Spotipy 的帮助下实现了一个简单的授权码流程。也许这对其他人也有帮助。同样在 github 上:https://github.com/perelin/spotipy_oauth_demo

代码如下:

from bottle import route, run, request
import spotipy
from spotipy import oauth2

PORT_NUMBER = 8080
SPOTIPY_CLIENT_ID = 'your_client_id'
SPOTIPY_CLIENT_SECRET = 'your_client_secret'
SPOTIPY_REDIRECT_URI = 'http://localhost:8080'
SCOPE = 'user-library-read'
CACHE = '.spotipyoauthcache'

sp_oauth = oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI,scope=SCOPE,cache_path=CACHE )

@route('/')
def index():

access_token = ""

token_info = sp_oauth.get_cached_token()

if token_info:
print "Found cached token!"
access_token = token_info['access_token']
else:
url = request.url
code = sp_oauth.parse_response_code(url)
if code:
print "Found Spotify auth code in Request URL! Trying to get valid access token..."
token_info = sp_oauth.get_access_token(code)
access_token = token_info['access_token']

if access_token:
print "Access token available! Trying to get user information..."
sp = spotipy.Spotify(access_token)
results = sp.current_user()
return results

else:
return htmlForLoginButton()

def htmlForLoginButton():
auth_url = getSPOauthURI()
htmlLoginButton = "<a href='" + auth_url + "'>Login to Spotify</a>"
return htmlLoginButton

def getSPOauthURI():
auth_url = sp_oauth.get_authorize_url()
return auth_url

run(host='', port=8080)

关于python - spotipy授权代码流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25711711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com