Issue Description
I built a Python script that processes music data from Spotify playlists and exports everything to CSV format. The script pulls information about songs, musicians, and albums from multiple playlists using the Spotify Web API.
The Problem
My script runs fine for roughly one hour, then freezes without showing any error messages. It just stops processing tracks and hangs there. I think this happens because the authentication token expires.
I tried adding token refresh logic at the start of my script, but now it gets stuck on the very first song instead of running for an hour like before. The console output just shows “Processing track” and then nothing else happens.
What I Tried
I added code to refresh the access token before the main loop starts. I also switched from user authentication to client credentials flow, thinking it might be more stable. Neither approach worked.
Current Code Structure
import csv
from datetime import datetime, timedelta
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import time
# Authentication setup
client_id = 'your_client_id'
client_secret = 'your_client_secret'
auth_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
spotify_client = spotipy.Spotify(auth_manager=auth_manager)
# List of playlist IDs to process
playlist_list = ['37i9dQZF1DX4JAvHpjipBk', '37i9dQZF1DX0XUsuxWHRQd', '37i9dQZF1DXdwmD5Q7Gxah']
music_data = []
def renew_token():
spotify_client.auth_manager.get_access_token(as_dict=False, check_cache=False)
renew_token()
# Main processing loop
for playlist_id in playlist_list:
playlist_info = spotify_client.playlist(playlist_id)
track_results = spotify_client.playlist_tracks(playlist_id)
position = 1
for item in track_results['items']:
current_track = item['track']
print(f"Processing: {current_track['artists'][0]['name']} - {current_track['name']}")
try:
artist_info = spotify_client.artist(current_track['artists'][0]['id'])
album_info = spotify_client.album(current_track['album']['id'])
music_data.append({
'musician': current_track['artists'][0]['name'],
'title': current_track['name'],
'release_date': current_track['album']['release_date'],
'playlist_position': position,
'artist_followers': artist_info['followers']['total'],
'cover_image': current_track['album']['images'][0]['url'],
'song_popularity': current_track['popularity'],
'musician_popularity': artist_info['popularity'],
'record_label': album_info['label'],
'playlist_id': playlist_id,
'playlist_title': playlist_info['name']
})
position += 1
except Exception as error:
print(f"Error processing track: {error}")
renew_token()
time.sleep(1)
Questions
- Why does my script freeze without throwing any error messages?
- How can I implement proper automatic token refresh during the data extraction process?
- Should I be using a different authentication method for long-running scripts?
Any help would be appreciated. Thanks!