$ curl https://api.goclimate.com/v1/flight_footprint \
-u YOUR_API_KEY: \
-d 'segments[0][origin]=ARN' \
-d 'segments[0][destination]=BCN' \
-d 'segments[1][origin]=BCN' \
-d 'segments[1][destination]=ARN' \
-d 'cabin_class=economy' \
-d 'currencies[]=SEK' \
-d 'currencies[]=USD' \
-G
我有以下輸入,由 API 的創建者作為示例提供。此輸入旨在用于終端并以字典的形式提供輸出。如何將上面的輸入寫入串列或字典中以將其用作 Python 腳本的一部分?我像下面這樣嘗試過,但來自 API 的回應僅僅是b' '
payload = {
"segments" : [
{
"origin" : "ARN",
"destination" : "BCN"
},
{
"origin" : "BCN",
"destination" : "ARN"
}
],
"cabin_class" : "economy",
"currencies" : [
"SEK", "USD"
]
}
r = requests.get('https://api.goclimate.com/v1/flight_footprint', auth=('my_API_key', ''), data=payload)
print(r.content)
uj5u.com熱心網友回復:
您正在使用 發出 GET 請求requests,但您正在嘗試通過data,這適用于發出 POST 請求。在這里你想params改用:
response = requests.get(
"https://api.goclimate.com/v1/flight_footprint",
auth=("my_API_key", ""),
params=payload,
)
print(response.content)
現在,應該payload是什么?它可以是字典,但不能以您擁有它的方式嵌套,因為它需要作為引數編碼到 URL 中(注意,這是您-G在 curl 請求中所做的選擇)。
查看檔案和您的curl示例,我認為應該是:
payload = {
"segments[0][origin]": "ARN",
"segments[0][destination]": "BCN",
"segments[1][origin]": "BCN",
"segments[1][destination]": "ARN",
"cabin_class": "economy",
"currencies[]": "SEK", # this will actually be overwritten
"currencies[]": "USD", # since this key is a duplicate (see below)
}
response = requests.get(
"https://api.goclimate.com/v1/flight_footprint",
auth=("my_API_key", ""),
params=payload,
)
print(response.content)
考慮一下我們如何將您的原始字典決議為這種結構:
data = {
"segments" : [
{
"origin" : "ARN",
"destination" : "BCN"
},
{
"origin" : "BCN",
"destination" : "ARN"
}
],
"cabin_class" : "economy",
"currencies" : [
"SEK", "USD"
]
}
payload = {}
for index, segment in enumerate(data["segments"]):
origin = segment["origin"]
destination = segment["destination"]
# python 3.6 needed:
payload[f"segments[{index}][origin]"] = origin
payload[f"segments[{index}][destination]"] = destination
payload["cabin_class"] = data["cabin_class"]
# requests can handle repeated parameters with the same name this way:
payload["currencies[]"] = data["currencies"]
......應該這樣做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451057.html
上一篇:檢查字典中的多個kv
下一篇:如何從字典串列中獲取唯一值?
