Home > Mobile >  Get Spotify access token with spotipy on Django and Python
Get Spotify access token with spotipy on Django and Python

Time:02-11

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?

CodePudding user response:

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']

CodePudding user response:

The solution was to create a new view to access the URL

views.py

@authenticated_user
def spotify_login(request):
    #cerca nel json
    my_loaded_dict = {}
    with open('spotify_auth.json', 'r') as f:
        try:
            my_loaded_dict = json.load(f)
        except:
            pass
    if str(request.user.username) in my_loaded_dict:
        messages.error(request, "You have already linked your Spotify account")
        return HttpResponseRedirect('account/'   str(request.user.username))

    sp_auth = oauth2.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/members/spotify_callback",
                                  scope="user-library-read")
    redirect_url = sp_auth.get_authorize_url()
    return HttpResponseRedirect(redirect_url)


@authenticated_user
def spotify_callback(request):
    full_path = request.get_full_path()
    parsed_url = urlparse(full_path)
    spotify_code = parse_qs(parsed_url.query)['code'][0]
    data = {
        str(request.user.username): spotify_code
    }
    with open('spotify_auth.json', 'w') as f:
        json.dump(data, f)

    messages.success(request, "You have correctly linked your Spotify account")

    return HttpResponseRedirect('account/'   str(request.user.username))

urls.py

urlpatterns = [
    path('account/<str:username>/', views.account_user, name="account"),
    path('spotify_login', views.spotify_login, name="spotify_login"),
    path('spotify_callback', views.spotify_callback, name="spotify_callback"),
]

The code also saves the token in a JSON and search for it if it has already been saved

  • Related