spotipy 授权码流程 [英] spotipy authorization code flow

查看:48
本文介绍了spotipy 授权码流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the Spotipy python library to interact with the Spotify web api. I have worked through the API and docs but I do not see a clear example that shows how the library supports the Authorization code flow ( https://developer.spotify.com/web-api/authorization-guide/#authorization-code-flow ).

推荐答案

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

I implemented a simple Authorization Code flow with the help of Spotipy. Maybe this is helpful for other people as well. Also on 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)

这篇关于spotipy 授权码流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆