将终端输入转换为python字典,以便与API一起使用


$ 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)

您正在使用requests发出GET请求,但您正在尝试传递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"]

应该这样做。

最新更新