use*_*779 6 python spotify oauth-2.0 spotipy
我正在使用Spotipy python库与Spotify web api进行交互.我已经完成了API和文档,但是我没有看到一个明确的示例,它显示了库如何支持授权代码流(https://developer.spotify.com/web-api/authorization-guide/#authorization-code-流动).
我在 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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8679 次 |
最近记录: |