将终端输入转换为 python 字典以供 API 使用

Convert terminal input to python dictionary for use with 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 作为参数(N.B。这就是你的 -G 选项在 curl 请求中执行)。

Looking at the docs和你的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"]

...应该这样做。