如何使用变量的值作为 HTTP POST 参数?

How to use variable's value as HTTP POST parameter?

我正在尝试向 API 发送 HTTP post 请求,但我没有使用预设文本值作为 POST 数据,而是尝试使用变量,但可以似乎不知道该怎么做?

这是代码:

url1 = "https://example.com/api/req"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
data = """
{
    "type": "Direction",
    "station": "Dept",
    "status": "check",
    "values": {
        "Par1": "5",
        "Par2" : "2",
        "Par3": "3",
        "Par4": "1",
        "Par5": "4"
    }
}
"""
resp1 = requests.post(url1, headers=headers, data=data)

所以我没有使用 "type": "Direction" 这样的东西,而是尝试使用 "type": Variable_1.

如何才能做到这一点?

正如@CaiAllin 指出的那样,您可以像这样向请求传递 Python 字典:

import json
import requests
from requests.structures import CaseInsensitiveDict

url1 = "https://example.com/api/req"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"

type_ = "Direction"
station = "Dept"
status = "check"
values = {
    "Par1": "5",
    "Par2": "2",
    "Par3": "3",
    "Par4": "1",
    "Par5": "4",
}

data = {
    "type": type_,
    "station": station,
    "status": status,
    "values": values,
}

resp1 = requests.post(url1, headers=headers, data=json.dumps(data))

您可以使用 f-string(只要您使用的是 Python 3.7+)。

url1 = "https://example.com/api/req"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
Variable_1 = "Direction"
data = f"""
{{
    "type": "{Variable_1}",
    "station": "Dept",
    "status": "check",
    "values": {{
        "Par1": "5",
        "Par2" : "2",
        "Par3": "3",
        "Par4": "1",
        "Par5": "4"
    }}
}}
"""
resp1 = requests.post(url1, headers=headers, data=data)