将变量插入数据请求字典 python
insert variable into data request dictionary python
我正在尝试使用 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 期望请求 body 为 json
,您目前正在手动构建。但是,您似乎使用了拼写错误的 header:Content.Type
而不是 Content-Type
(点而不是破折号).
幸运的是,python requests
库可以 encode python objects into json for you and add the Content-Type
headers automatically. It can also add the parameters to the 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}"},
)
让请求库为您完成工作!
我正在尝试使用 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 期望请求 body 为 json
,您目前正在手动构建。但是,您似乎使用了拼写错误的 header:Content.Type
而不是 Content-Type
(点而不是破折号).
幸运的是,python requests
库可以 encode python objects into json for you and add the Content-Type
headers automatically. It can also add the parameters to the 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}"},
)
让请求库为您完成工作!