我正在尝试使用Spotify Web API创建并填充播放列表。我正在遵循this官方参考,并且正在将Python 3与requests模块一起使用。这是我的代码:
def spotify_write_playlist(auth, name, tracks, public=True):
ids = []
for track in tracks:
track_id = track.services['spotify']
if track_id: ids.append(track_id)
headers = {
"authorization":"Bearer " + auth.token,
"content-type":"application/json"
}
data = {
"name":name,
"public":public
}
r = makeRequest("https://api.spotify.com/v1/users/" + auth.username + "/playlists", "post", 201, json=data, headers=headers)
playlist_id = json.loads(r.content)['id']
data = {"uris":ids}
r = makeRequest("https://api.spotify.com/v1/users/" + auth.username + "/playlists/" + playlist_id + "/tracks", "post", 201, json=data, headers=headers)
return playlist_id
def makeRequest(url, method="get", expectedCode=200, *args, **kwargs):
while True:
r = requests.request(method, url, **kwargs)
if r.status_code == 429:
time.sleep(TMR_DELAY)
continue
elif r.status_code == expectedCode:
return r
else:
if "spotify.com" in url:
raise spotify.ApiError(r.status_code, expectedCode, r.content)
else:
raise youtube.ApiError(r.status_code, expectedCode, r.content)
makeRequest函数是用于处理速率限制的request.request的包装。
上面的代码与一堆示例轨道一起运行时,在第一次调用makeRequest时返回错误400,因此我的示例轨道不会成为问题,因为该调用只涉及名称和公共变量。>
错误响应没有正文,因此没有错误描述。这表明我可能缺少一些非常明显的东西。有人可以帮忙吗?
答案 0 :(得分:0)
播放列表创建请求停止了错误,我不知道为什么。在尝试诊断问题时,我必须更改所有错误。我以为它试图创建一个同名的播放列表,但Spotify允许重复的播放列表。也许我使用的令牌或令牌对象有问题。抱歉。
但是,当清除上一个时,我还发现了另一个问题:在添加到轨道中时,您不仅指定了轨道ID(abcdef123),还指定了轨道uri(spotify:track:abcdef123)。我修改了以下的Spotify_write_playlists:
def spotify_write_playlist(auth, name, tracks, public=True):
ids = []
for track in tracks:
track_id = track.services['spotify']
if track_id: ids.append("spotify:track:"+track_id)
headers = {
"authorization":"Bearer " + auth.token,
"content-type":"application/json"
}
data = {
"name":name,
"public":public
}
r = makeRequest("https://api.spotify.com/v1/users/" + auth.username + "/playlists", "post", 201, json=data, headers=headers)
playlist_id = json.loads(r.content)['id']
data = {"uris":ids}
r = makeRequest("https://api.spotify.com/v1/users/" + auth.username + "/playlists/" + playlist_id + "/tracks", "post", 201, json=data, headers=headers)
return playlist_id