1

So I'm iterating over a huge .csv file which each row contains a song name and an artist name. For each of these rows I have to write into another file the track id of this song. I have been running the program but I get this error after an hour:
"The access token expired"
I been reading and it seems the token expires after an hour. Is there any way I can reload the token during my execution?
This is the function I wrote to get the song ID

def getSongId(artist, title, songMap):
index = artist + title
trackId = 'null'

try:
    trackId = songMap[index]
    print("HashMap used")
except KeyError:
    try:
        resultats = spotify.search(q='artist:' + artist + ' track:' + title, type='track')
        trackId = resultats['tracks']['items'][0]['id']
        songMap[index] = trackId
    except IndexError:
        trackId = 'null'
return trackId, songMap  

This is the error I get:

spotipy.client.SpotifyException: http status: 401, code:-1 - https://api.spotify.com/v1/search?q=artist%3AZadye+Wolf+track%3AHustler&limit=10&offset=0&type=track: The access token expired

Thanks you very much

sergi martinez
  • 165
  • 1
  • 8
  • Possible duplicate of [Spotipy Refreshing a token with authorization code flow](https://stackoverflow.com/questions/49239516/spotipy-refreshing-a-token-with-authorization-code-flow) – Jack Moody Mar 31 '19 at 17:40

1 Answers1

0

Simple solution would be to catch the exception when the token expires and refresh the token before continuing.

try:
    result = spotify.search(...)
except spotify.client.SpotifyException as e:
    token = refresh_token(...)
else:
   # normal flow
rdas
  • 20,604
  • 6
  • 33
  • 46
  • I'm trying this. Let's see what happens after an hour... Thanks! – sergi martinez Mar 31 '19 at 18:11
  • Okay I tried and didn't work. I think the problem is at refreshing the token, because if I print the new and old token it gives the same value. How would the refresh token function look like? – sergi martinez Mar 31 '19 at 21:29