如何授权在 Django 上使用 Spotipy?

How do I authorize using Spotipy on Django?

我在尝试授权 Spotipy 时遇到了很多麻烦。它在 IDLE 中运行良好,但一旦我尝试与 Django 一起完成它,他妈的就会松懈。我走得最远的地方是我从回调中获得代码的地方。但是在那之后我该怎么办? 下面这段代码需要

def add_song(request, pk, uri):
    scope = "user-read-recently-played user-top-read user-read-playback-position user-read-playback-state user-modify-playback-state user-read-currently-playing user-read-private playlist-modify-private playlist-read-private"
    token = util.prompt_for_user_token("username", scope, client_id=SECRET,client_secret=SECRET,redirect_uri='http://localhost:8000/rooms/callback/')
    sp = spotipy.Spotify(auth=token)
    sp.add_to_queue(uri)

    auth_manager = spotipy.oauth2.SpotifyOAuth(scope='user-read-currently-playing playlist-modify-private', show_dialog=True)
    
    
    if request.GET.get("code"):
        # Step 3. Being redirected from Spotify auth page
        auth_manager.get_access_token(request.GET.get("code"))
        return redirect('/')

    return render(request, 'rooms/{0}.html'.format(pk))

def callback(request):    
    return redirect(reverse("index"))

URL 模式:

urlpatterns = [
    path('<int:pk>/add_song/<str:uri>', views.add_song, name='add_song'),
    path('callback/<str:token>', views.callback, name="callback")
]

我真的需要一些东西来继续。我一直在谷歌搜索,但我真的不知道该怎么做。您能否提供 Django Python 授权示例或尝试帮助我?

不要使用 util.prompt_for_user_token。假设您希望不同的用户使用您的应用程序,您将如何预先知道他们的用户名?

改为使用 SpotifyOAuth 对象(您正在使用它,只是不是以我将要展示的方式)。可以参考官方文档的客户端Authorization Code Flow部分。

基本情况如下:

# Seprating the login from add_song()
def login(request):
        sp_auth = SpotifyOAuth(
        scope=scope,
        client_id=client_id,
        client_secret=client_secret,
        redirect_uri=redirect_uri,
        )
        # This url will prompt you a Spotify login page, then redirect user to your /callback upon authorization
        redirect_url = sp_auth.get_authorize_url() # Note: You should parse this somehow. It may not be in a pretty format.
        return redirect(redirect_url)

# You can make add_song() and callback() the same function. 
# If you have multiple pages where you need to use the API, I suggest caching the token here as well.
def callback_and_add_song():
        sp_auth = [the same as above. You should make a method to modularize it.]
        # Get code from url
        code = request.GET.get("code", "")
        token = sp_auth.get_access_token(code=code)
        <You have token now. Do what you need.>

我在您的代码中注意到了一些可能不需要/错误的事情:

  1. path('callback/<str:token>':我不认为 <str:token> 必须在那里。
  2. return redirect('/'):在 add_song() 中的第一个 if 中,假设您之前的代码有效,您仍然只是重定向到某个地方而没有缓存令牌/传递它。
  3. return redirect(reverse("index")):同上。我认为为了性能和所有,你应该在 callback() 中缓存令牌,然后重定向到你实际使用它的页面。