Skip to content
Advertisement

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?

Advertisement

Answer

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

views.py

from .utils import is_user_already_auth_spotify, spotify_oauth2

@authenticated_user
def spotify_login(request):

    if is_user_already_auth_spotify(request.user.username):
        messages.error(request, "You have already linked your Spotify account")
        return HttpResponseRedirect('account/' + str(request.user.username))

    sp_auth = spotify_oauth2()
    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]

    sp_auth = spotify_oauth2()
    token = sp_auth.get_access_token(spotify_code)

    data = {
        str(request.user.username): token
    }
    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"),
]

utils.py

import json
from spotipy import oauth2
import os


def is_user_already_auth_spotify(username):
    my_loaded_dict = {}
    with open('spotify_auth.json', 'r') as f:
        try:
            my_loaded_dict = json.load(f)
        except:
            # file vuoto
            pass
    if str(username) in my_loaded_dict:
        # controllare scadenza token ed in caso rinnovarlo
        return True
    else:
        return False


def spotify_oauth2():
    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")
    return sp_auth

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement