I am retrieving track data from spotify api for a total of 10 tracks, but it takes around 2-3 seconds to run. Is there any way to speed it up by using some python libraries like multiprocessing or something else.
track_url = []
track_name = []
album_image = []
for i in range(len(tracks_recommend)):
track_id = tracks_recommend.at[i, 'id']
# call to spotify api
res = spotify.track(track_id=track_id)
track_url.append(res['external_urls'])
track_name.append(res['name'])
album_image.append(res['album']['images'][0]['url'])
>Solution :
Is there any way to speed it up by using some python libraries like multiprocessing
Yes, multiprocess works great running API requests in parallel. This will get you started:
from multiprocessing.pool import ThreadPool as Pool
def recommend(track_id):
return spotify.track(track_id=track_id)
track_ids = [tracks_recommend.at[i, 'id']
for i in range(len(tracks_recommend))]
with Pool(5) as pool:
for res in pool.map(recommend, track_ids):
...