You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am trying to extract information about artists, albums and songs. The problem comes when after one iteration (approximately 1000 songs, 1000 albums and 1200 artists), the API stops working, but without returning a 429 error code or anything, it just waits, so I can't handle exceptions of any kind.
I have tried to make a custom session of requests to prevent it from staying in the retry state indefinitely but it does not react.
This code is only to extract tracks info:
importcsvimportosimportjsonimportrandomimportspotipyimporttimefromdatetimeimportdatetimefromdateutilimportparserasdate_parserfromdateutil.parserimportParserErrorfromtqdmimporttqdmdefopen_chunk_id(n_json):
csv_file_path=f'output_chunks/chunk_{n_json}.csv'withopen(csv_file_path, newline='') ascsvfile:
track_ids_reader=csv.reader(csvfile)
next(track_ids_reader) # Skip the header rowtrack_ids= [row[0] forrowintrack_ids_reader]
returntrack_idsdeffetch_track_info_from_csv(track_ids, access_token):
track_data= []
sp=spotipy.Spotify(auth=access_token)
scrapped_time=datetime.now()
fortrack_idintqdm(track_ids, desc='Fetching track information', position=0):
try:
time.sleep(random.uniform(0, 0.5))
track_info=sp.track(str(track_id))
track_data.append({
'Track ID': track_id,
'Track Name': track_info['name'],
'Artist(s)': [artist['name'] forartistintrack_info['artists']],
'Album': track_info['album']['name'],
'Release Date': track_info['album']['release_date'],
'Popularity': track_info['popularity'],
'Duration (ms)': track_info['duration_ms'],
'Explicit': track_info['explicit'],
'Track Number': track_info['track_number'],
'URI': track_info['uri'].replace('spotify:track:', ''),
'Album ID': track_info['album']['id'],
'Artist ID(s)': [artist['id'] forartistintrack_info['artists']],
'Scrapped Time': scrapped_time.strftime('%Y-%m-%d %H:%M:%S')
})
exceptExceptionase:
print(f"Failed to fetch information for track ID {track_id}: {str(e)}")
returntrack_datadefsave_track_data_to_json(track_data, output_json_file):
# Restructure data to match JSON formatjson_data= []
fortrack_infointrack_data:
try:
parsed_date=date_parser.parse(track_info['Release Date'])
ifparsed_date.day==1:
# Case 1: Only year providedrelease_date=parsed_date.strftime('%Y-01-01')
else:
# Case 3: All info providedrelease_date=parsed_date.strftime('%Y-%m-%d')
exceptParserError:
print(f"ParserError: Failed to parse release date for track ID {track_info['Track ID']}. Setting release date to only year.")
# Set release_date to only the yearrelease_date=parsed_date.strftime('%Y-01-01')
exceptValueError:
print(f"ValueError: Failed to parse release date for track ID {track_info['Track ID']}. Setting release date to only year.")
# Set release_date to only the yearrelease_date=parsed_date.strftime('%Y-01-01')
exceptExceptionase:
print(f"Failed to parse release date for track ID {track_info['Track ID']}: {str(e)}")
# Default to None if parsing failsrelease_date=Nonejson_data.append({
'Track ID': track_info['Track ID'],
'Track Name': track_info['Track Name'],
'Artist(s)': track_info['Artist(s)'],
'Album': track_info['Album'],
'Release Date': release_date,
'Popularity': track_info['Popularity'],
'Duration (ms)': track_info['Duration (ms)'],
'Explicit': track_info['Explicit'],
'Artist ID(s)': track_info['Artist ID(s)'],
'Track Number': track_info['Track Number'],
'Album ID': track_info['Album ID'],
'URI': track_info['URI'],
'Scrapped Time': track_info['Scrapped Time']
})
# Save data to JSON filewithopen(output_json_file, 'w', encoding='utf-8') asjson_file:
json.dump(json_data, json_file, ensure_ascii=False, indent=4)
print(f"Track information saved to {output_json_file}")
I need to know how to keep getting data from the API without the credentials being unusable, since doing calculations, the ratelimit that Spotify says is not exceeded. Otherwise, I need the API to return an error code to handle the exception and be able to pivot between multiple credentials.
After a complete and successful execution, I re-launch the script and at one point, the API stops at this point and does not return any errors. I re-launch the script with the same credentials, and it does not start, as they have been unusable for at least 24 hours.
Environment:
macOS Sonoma 14.2.1
Python 3.11.2
spotipy last version
Pycharm
Additional context
Add any other context about the problem here.
The text was updated successfully, but these errors were encountered:
I'm having the same issue with sp.album_tracks(). It just stops without returning any error. When I try stepping into function with the debugger, it never actually gets there. It just waits.
Yeah, it's a rate limit issue. When I try just calling the API directly using requests, I get a 429. Something about how spotipy is wrapping the API is stalling, rather than returning the 429.
I am trying to extract information about artists, albums and songs. The problem comes when after one iteration (approximately 1000 songs, 1000 albums and 1200 artists), the API stops working, but without returning a 429 error code or anything, it just waits, so I can't handle exceptions of any kind.
I have tried to make a custom session of requests to prevent it from staying in the retry state indefinitely but it does not react.
This code is only to extract tracks info:
I need to know how to keep getting data from the API without the credentials being unusable, since doing calculations, the ratelimit that Spotify says is not exceeded. Otherwise, I need the API to return an error code to handle the exception and be able to pivot between multiple credentials.
After a complete and successful execution, I re-launch the script and at one point, the API stops at this point and does not return any errors. I re-launch the script with the same credentials, and it does not start, as they have been unusable for at least 24 hours.
Environment:
Additional context
Add any other context about the problem here.
The text was updated successfully, but these errors were encountered: