如何加快 Spotify API 通话速度?
How to speed up Spotify API calls?
我正在从 spotify api 中检索总共 10 首曲目的曲目数据,但 运行 大约需要 2-3 秒。有什么方法可以通过使用一些 python 库来加速它,比如 multiprocessing 或其他东西。
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'])
Is there any way to speed it up by using some python libraries like multiprocessing
是的,多进程可以很好地并行处理 运行 API 请求。这将使您入门:
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):
...
取决于 Spotify 是否跟踪您并将您限制为一个请求。如果他们不这样做,这就是您可以开始的:
def process_track(track_id)
# call to spotify api
res = spotify.track(track_id=track_id)
return (res['external_urls'], res['name'], res['album']['images'][0]['url'])
with Pool(4) as p: # replace 4 with whatever number you want
track_ids = [tracks_recommend.at[i, 'id'] for i in range(len(tracks_recommend))]
output = p.map(process_track, track_ids)
track_url, track_name, album_image = zip(*output)
这不会帮助您解决延迟问题,但可能会增加吞吐量。
我正在从 spotify api 中检索总共 10 首曲目的曲目数据,但 运行 大约需要 2-3 秒。有什么方法可以通过使用一些 python 库来加速它,比如 multiprocessing 或其他东西。
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'])
Is there any way to speed it up by using some python libraries like multiprocessing
是的,多进程可以很好地并行处理 运行 API 请求。这将使您入门:
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):
...
取决于 Spotify 是否跟踪您并将您限制为一个请求。如果他们不这样做,这就是您可以开始的:
def process_track(track_id)
# call to spotify api
res = spotify.track(track_id=track_id)
return (res['external_urls'], res['name'], res['album']['images'][0]['url'])
with Pool(4) as p: # replace 4 with whatever number you want
track_ids = [tracks_recommend.at[i, 'id'] for i in range(len(tracks_recommend))]
output = p.map(process_track, track_ids)
track_url, track_name, album_image = zip(*output)
这不会帮助您解决延迟问题,但可能会增加吞吐量。