【发布时间】:2018-09-14 17:29:32
【问题描述】:
我正在开发一个程序,当我的艺术家在 Spotify 上发布新音乐时,它会向我发送电子邮件。它通过在脚本运行时获取每个艺术家拥有的专辑数量并将结果与前一天保存为 CSV 文件的结果进行比较来实现这一点。
这涉及到 API 调用来验证艺术家是否在 Spotify 上(我收到的错误是某些专辑不在 Spotify 上),然后获取该艺术家的专辑数量。这些电话非常耗时,尤其是当我有接近一千位艺术家时。
我想知道如何并行化这些 API 调用或任何其他建议以加快整个程序的速度。下面链接的是具有 API 调用的代码部分。提前感谢您的时间。
# given artist name returns all info related to artist
def get_artist_info(spotipy_instance, name):
results = spotipy_instance.search(q='artist:' + name, type='artist')
items = results['artists']['items']
if len(items) > 0:
return items[0]
else:
return None
# returns list of all albums given artist name
def get_artist_albums(spotipy_instance, artist):
albums = []
results = spotipy_instance.artist_albums(artist['id'], album_type='album')
albums.extend(results['items'])
while results['next']:
results = spotipy_instance.next(results)
albums.extend(results['items'])
seen = set() # to avoid dups
for album in albums:
name = album['name']
# print(album['name'] + ": " + album['id'])
if name not in seen:
seen.add(name.encode('utf-8'))
return list(seen)
def get_all_artists_info(spotipy_instance, list_of_all_artists):
all_artist_info = []
print("Getting number of albums for all artists")
# bar = Bar('Loading...', max=len(list_of_all_artists), suffix='%(index)d/%(max)d - %(percent).1f%% - %(eta)ds')
for artist_name in list_of_all_artists:
# increment_progress_bar(bar)
# print(artist_name)
artist_info = get_artist_info(spotipy_instance, artist_name)
if artist_info is not None:
albums = get_artist_albums(spotipy_instance, artist_info)
# print(albums)
artist = Artist(artist_name, len(albums), albums)
all_artist_info.append(artist)
else:
print("\nCan't find " + artist_name)
artist = Artist(artist_name, -1, [])
all_artist_info.append(artist)
# print(" ")
# bar.finish()
print("Done!\n")
all_artist_info.sort(key=lambda artist: artist.name)
return all_artist_info
【问题讨论】:
标签: python parallel-processing python-requests spotify