Python 3.x 如何将变量传递到有效负载

Python 3.x 如何将变量传递到有效负载,python-3.x,python-requests,Python 3.x,Python Requests,因此,我有一个端点,我正在尝试将其集成到Python中,该端点接受POST请求,根据API文档,有效负载的格式如下: payload = "{\r\n\"serviceCode\" : \"V-TV\",\r\n\"type\" : \"DSTV\",\r\n\"smartCardNo\" : \"10441003943\"\r\n}\r\n\r\n\r\n\r\n\

因此,我有一个端点,我正在尝试将其集成到Python中,该端点接受POST请求,根据API文档,有效负载的格式如下:

payload = "{\r\n\"serviceCode\" : \"V-TV\",\r\n\"type\" : \"DSTV\",\r\n\"smartCardNo\" : \"10441003943\"\r\n}\r\n\r\n\r\n\r\n\r\n"
我希望type和smartCardNo的值是动态的,也就是说,我将从前端的表单中获取值并将其传递到后端,但我发现很难做到这一点。 如果我以这种方式格式化有效负载(这当然允许轻松传递变量):

我得到这个错误:

{'required_fields': ['The service code field is required.'], 'message': 'Service Code is not supplied', 'status': '301'}

有谁能告诉我如何以fist格式(文档中指定的格式)动态传递type和smartCardNo的值…非常感谢您的帮助。

您只需使用.format()

输出:

'{"serviceCode":"V-TV","type":"DSTV","smartCardNo":"10441003943"}'
如果您确实需要与
有效负载
示例中相同的格式,请简单使用:

payload = "{{\r\n\"serviceCode\" : \"{serviceCode}\",\r\n\"type\" : \"{mytype}\",\r\n\"smartCardNo\" : \"{smartCardNo}\"\r\n}}\r\n\r\n\r\n\r\n\r\n".format(
    serviceCode = dict_values["serviceCode"],
    mytype = dict_values["type"],
    smartCardNo = dict_values["smartCardNo"]
)
您的输出将是:

'{\r\n"serviceCode" : "V-TV",\r\n"type" : "DSTV",\r\n"smartCardNo" : "10441003943"\r\n}\r\n\r\n\r\n\r\n\r\n'

如果答案对你有用,请接受它。非常感谢。
payload = "{{\r\n\"serviceCode\" : \"{serviceCode}\",\r\n\"type\" : \"{mytype}\",\r\n\"smartCardNo\" : \"{smartCardNo}\"\r\n}}\r\n\r\n\r\n\r\n\r\n".format(
    serviceCode = dict_values["serviceCode"],
    mytype = dict_values["type"],
    smartCardNo = dict_values["smartCardNo"]
)
'{\r\n"serviceCode" : "V-TV",\r\n"type" : "DSTV",\r\n"smartCardNo" : "10441003943"\r\n}\r\n\r\n\r\n\r\n\r\n'