'Get Spotify access token with spotipy on Django and Python

I'm new to Django and I'm trying to link Spotify to my webapp. I'm using Spotify to do it and it correctly access to Spotify.

To do it I have a button that opens the view below

views.py

@authenticated_user
def spotify_login(request):

    sp_auth = SpotifyOAuth(client_id=str(os.getenv('SPOTIPY_CLIENT_ID')),
                           client_secret=str(os.getenv('SPOTIPY_CLIENT_SECRET')),
                           redirect_uri="http://127.0.0.1:8000/",
                           scope="user-library-read")
    redirect_url = sp_auth.get_authorize_url()
    auth_token = sp_auth.get_access_token()
    print(auth_token)
    print("----- this is the AUTH_TOKEN url -------", auth_token)
    return HttpResponseRedirect(redirect_url)

If I don't use auth_token = sp_auth.get_access_token() everything works fine and I got redirected to the correct. Unfortunately, if I add that line of code to access the access token, instead of staying on the same page, it opens another tab on the browser with the Spotify auth_code and lets the original page load forever.

Is there a way to retrieve the access token in the background without making my view reload or open another tab in the browser?



Solution 1:[1]

You are being redirected to exactly where you are telling django to go.

redirect_url is just a spotify api redirect containing a code, which is captured and used to get the access token.

Set your expected response as return value.

By the way, keep in mind:

  1. redirect_uri="http://127.0.0.1:8000/", should be added in spotify app (usually as http://127.0.0.1:8000/callback",)
  2. auth_token is a json, you can find token in auth_token['access_token']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman