代码之家  ›  专栏  ›  技术社区  ›  theParanoidAndroid

Spotify Web API-创建播放列表时没有正文的错误400

  •  1
  • theParanoidAndroid  · 技术社区  · 6 年前

    我正在尝试使用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函数是处理ratelimiting的requests.request的包装器。

    上面的代码在第一次调用makeRequest时用一堆样本跟踪运行时返回一个错误400,因此我的样本跟踪不能成为问题,因为只有名称和公共变量与该调用有关。

    错误响应没有正文,因此没有错误描述。这表明我可能遗漏了一些非常明显的东西。有人能帮忙吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   theParanoidAndroid    6 年前

    播放列表创建请求停止出错,我不知道原因。当我试图诊断这个问题时,我必须改变任何错误。我以为它试图创建一个同名的播放列表,但spotify允许重复播放列表。可能我使用的令牌或令牌对象有问题。对不起的。

    但是,在清除前一个问题时,我还发现了另一个问题:添加到曲目时,指定的是曲目uri(spotify:track:abcdef123),而不仅仅是曲目id(abcdef123)。我修改了spotify的以下播放列表:

    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