如何在Django中使用spotify api身份验证重定向uri?

时间:2016-06-30 21:24:31

标签: python ajax django oauth spotipy

我在Django中构建了一个使用Spotify API,Spotify API Python库的应用程序,并使用spotipy.util.prompt_for_user_token()命令生成令牌并访问我的私有库:

import spotipy
import spotipy.util as util
import os, ast

#Spotify API keys
scope = "playlist-read-private"
uir = "http://localhost:8000"
username = "<MY_USERNAME>"

spotify_uid = os.environ["SPOTIFY_UID"]
spotify_usec = os.environ["SPOTIFY_USEC"]
print "retrieved keys from OS"

#set up access
def get_access():
  try:
    token = util.prompt_for_user_token(username, scope, spotify_uid, spotify_usec, uir)
    print "SUCCESS"
    return spotipy.Spotify(auth=token)
  except:
    print "FAILED TO LOAD"

我希望应用程序能够使用ui登录而不是硬编码登录,但我无法弄清楚如何使用。

目前我已经登录了&#39;尝试通过Javascript触发登录页面重定向的按钮,通过使用用户名参数调用上面的代码,但是打开一个新页面,以下内容在控制台中:

User authentication requires interaction with your
        web browser. Once you enter your credentials and
        give authorization, you will be redirected to
        a url.  Paste that url you were directed to to
        complete the authorization.


Opening https://accounts.spotify.com/authorize?scope=playlist-read-     private&redirect_uri=http%3A%2F%2Flocalhost%3A8000&response_type=code&client_id=<CLIENT_ID> in your browser


Enter the URL you were redirected to: [30/Jun/2016 15:53:54] "GET /?code=<TOKEN>HTTP/1.1" 200 2881 

注意: 克拉括号中的文字已被替换,因为它们是私钥。

我希望它具有与此网站处理登录方式类似的功能: http://static.echonest.com/SortYourMusic/

1 个答案:

答案 0 :(得分:0)

为了实现这一点,我最终放弃了spotipy模块,只使用了javascript。我看到你使用用户授权api流,这很好,因为你的服务器可以安全地发送你的密钥。将其移至应用程序的前端时,您无法执行此操作,而必须使用Implicit Grant流程:

#In your main page's <script>:
var loginSpotify = function(){
        var SPOTIPY_CLIENT_ID = "Your Client ID Here"
        var SPOTIPY_REDIRECT_URI = "Your Django Callback View Here (www.example.com/callback/)"
        var spotifyScope = "playlist-read-private"
        var spotifyAuthEndpoint = "https://accounts.spotify.com/authorize?"+"client_id="+SPOTIPY_CLIENT_ID+"&redirect_uri="+SPOTIPY_REDIRECT_URI+"&scope="+spotifyScope+"&response_type=token&state=123";
        window.open(spotifyAuthEndpoint,'callBackWindow','height=500,width=400');
        //This event listener will trigger once your callback page adds the token to localStorage
        window.addEventListener("storage",function(event){
            if (event.key == "accessToken"){
                var spAccessToken = event.newValue;
                //do things with spotify API using your access token here!!
            }
        });
    }

调用上述方法将打开一个新的弹出窗口,该窗口将引导用户通过spotify的登录。授权后,窗口将重定向到您指定的Django视图。让该视图加载一个回调页面,其唯一目的是从其URI中收集访问令牌:

#in your views.py:
def callback(request):
    return render(request, 'YourApp/spotifyLoginFinish.html',{})

当该页面加载时,在弹出窗口中,它的URI将包含您寻求的授权,例如:http://www.example.com/callback/#access_token=BQDoPzyrkeWu7xJegj3v1JDgQXWzxQk2lgXrQYonXkXIrhmjeJVS38PFthMtffwlkeWJlwejkwewlHaIaOmth_2UJ2xJrz2x-Voq0k0T0T4SuCUdIGY3w3cj5CpULkFla9zwKKjvdauM2KoUIQa1vULz-w8Da83x1&token_type=Bearer&expires_in=3600&state=123

Idk如果您使用的是jquery,但是有很多方法可以在页面加载时调用JS函数。所以现在你需要做的就是在回调页面加载后解析URI,你就可以得到你的访问令牌了。然后,您已完成此弹出回调窗口,因此您可以通过将访问令牌添加到localStorage来将其传递回主页面。请记住,在主页面上我们创建了一个事件监听器来观看localStorage,以便您知道它何时出现。这是您在回调页面上想要的代码示例(它使用了一些jquery,但是在页面加载时有常规的JS方法):

#In spotifyLoginFinish.html's <script>:
$('document').ready(function(){
        //i leave 'parseHash()' as an exercise for the reader, all it does is take the uri string(see above ex of what this looks like) and get the access_token from it
        var spotifyAccessToken = parseHash(String(window.location.hash));
        //you must clear localStorage for main page listener to trigger on all(including duplicate) entries
        localStorage.clear();
        localStorage.setItem('accessToken', spotifyAccessToken);
        window.close();
});

现在你的弹出窗口已关闭,你回到主窗口,在本帖子的第一段代码中的localStorage事件监听器函数中。它将从localStorage获取令牌并且您已完成所有设置!希望这会有所帮助,如果它不起作用,请发表评论。