我尝试将Spotify API与spotipy库结合使用,但我不了解本文中的代码示例:
https://towardsdatascience.com/making-your-own-discover-weekly-f1ac7546fedb
sourcePlaylist = sp.user_playlist("<source user>", "<Source Playlist ID>")
tracks = sourcePlaylist["tracks"]
songs = tracks["items"]
while tracks['next']:
tracks = sp.next(tracks)
for item in tracks["items"]:
songs.append(item)
我知道API返回的数据在嵌套字典中。我不明白为什么内部for循环是必要的。你知道吗
如果songs = tracks['items']
,那么while循环中的for循环基本上是:
for song in songs:
songs.append(song)
因为tracks['items']
本来就在列表中songs
。当songs
根据定义等于这个数据时,为什么要把tracks['items']
附加到songs
?你知道吗
之所以需要内部for循环,以及为什么重复将
tracks["items"]
添加到列表songs
中是有意义的,是因为Spotify API使用了分页来避免在API响应中返回比所需更多的数据。所以在while循环的每次迭代中tracks
都是不同的。你知道吗它是mentions it in the Spotify API Documentation,但它通常也是跨api发生的事情。例如,如果您有一个API端点返回Spotify上的歌曲列表,那么在单个响应中返回Spotify上的每首歌曲将是不切实际/不可能的。相反,这些数据将被分解成页。想要从Spotify检索所有歌曲的人会跟踪他们当前的“页面”,每次都会请求下一个页面,而只想在Spotify上检索歌曲子集的用户可能只会发出一个请求,而完全忽略页面功能。你知道吗
在示例中添加注释:
也可能有助于了解
sp.next
的实际作用:文章中的例子更加清晰(就像Tomerikoo用
extend
说的那样):相关问题 更多 >
编程相关推荐