我正试图用spotify API建立一个简单的唱机,我想将播放列表id保存在变量中,以便将来更容易更改或添加
import json
import requests
spotify_user_id = "...."
sgt_peppers_id = "6QaVfG1pHYl1z15ZxkvVDW"
class GetSongs:
def __init__(self):
self.user_id=spotify_user_id
self.spotify_token = ""
self.sgt_peppers_id = sgt_peppers_id
def find_songs(self):
query = "https://api.spotify.com/v1/me/player/play?
device_id=......"
headers={"Content.Type": "application/json", "Authorization": "Bearer
{}".format(self.spotify_token)}
data= '{"context_uri":"spotify:album:6QaVfG1pHYl1z15ZxkvVDW"}'
response = requests.put(query, headers=headers, data=data)
我希望它能像这样:数据= '{"context_uri" f" spotify:专辑:{sgt_peppers_id}"}">
,但遗憾的是它不起作用,所有其他的方法插入变量到字符串也不起作用。希望有人能回答这个问题。提前感谢!
Spotify API期望请求体为json
,您目前正在手工构建。但是,看起来你正在使用一个拼写错误的标题:Content.Type
而不是Content-Type
(点而不是破折号)。
幸运的是,pythonrequests
库可以为您将python对象编码为json并自动添加Content-Type
头文件。它还可以为您添加参数到url,因此您不必手动创建?query=string
。
# We can add this to the string as a variable in the `json={...}` arg below
album_uri = "6QaVfG1pHYl1z15ZxkvVDW"
response = requests.put(
"https://api.spotify.com/v1/me/player/play", # url without the `?`
params={"device_id": "..."}, # the params -- ?device_id=...
headers={"Authorization": f"Bearer {self.spotify_token}"},
json={"context_uri": f"spotify:album:{album_uri}"},
)
让请求库为你做这些工作!