I’m building a Python application that extracts music data from Spotify playlists and saves it to CSV format. The program was working fine initially, processing all songs from multiple playlists successfully. However, after running for about an hour, it started freezing during track processing.
I think this might be related to token expiration, so I added functionality to refresh the token at the start of my script. But now, instead of throwing any error messages, the program gets stuck on the very first song. Previously, it would process hundreds of tracks before stopping, but now it halts immediately.
I attempted to switch from SpotifyOAuth to SpotifyClientCredentials assuming it may help with authentication, but the problem continues. The script just hangs without any error output, which complicates debugging.
Here’s my current implementation:
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)
# Playlist IDs to process
playlist_collection = ['37i9dQZF1DX4JAvHpjipBk', '37i9dQZF1DX0XUsuxWHRQd', '37i9dQZF1DXdwmD5Q7Gxah']
song_data = []
def update_token():
spotify_client.auth_manager.get_access_token(as_dict=False, check_cache=False)
update_token()
# Process each playlist
for playlist_id in playlist_collection:
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"Working on: {current_track['artists'][0]['name']} - {current_track['name']}")
try:
artist_details = spotify_client.artist(current_track['artists'][0]['id'])
album_details = spotify_client.album(current_track['album']['id'])
song_data.append({
'performer': current_track['artists'][0]['name'],
'title': current_track['name'],
'release_date': current_track['album']['release_date'],
'playlist_position': position,
'artist_followers': artist_details['followers']['total'],
'cover_image': current_track['album']['images'][0]['url'],
'song_popularity': current_track['popularity'],
'artist_popularity': artist_details['popularity'],
'isrc_code': current_track['external_ids']['isrc'],
'record_label': album_details['label'],
'spotify_link': current_track['album']['external_urls']['spotify'],
'playlist_id': playlist_id,
'playlist_title': playlist_info['name']
})
position += 1
except spotipy.exceptions.SpotifyException:
update_token()
continue
except Exception as error:
print(f"Error processing track: {error}")
continue
time.sleep(1)
# Save to CSV
with open('spotify_data.csv', 'w', newline='') as output_file:
field_names = ['performer', 'title', 'release_date', 'playlist_position', 'artist_followers']
csv_writer = csv.DictWriter(output_file, fieldnames=field_names)
csv_writer.writeheader()
for song in song_data:
csv_writer.writerow(song)
Why is my script hanging without throwing any errors? How can I properly handle token refresh to keep the script running smoothly? Any suggestions for debugging this authentication issue would be really helpful.