为请求格式化Python字符串有效负载值

2024-10-03 21:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图替换python请求下面有效负载_1中的值;使用动态传递的参数值。payload_2应该看起来像payload_1,只有键日期和路由的值应该是我可以传入的变量

我无法更改头'Content-Type':'text/plain',因为服务器希望这样做

参数值是该格式中今天的_日期和路由_值

payload_1 = "{\n    \"ABCD\": [\n  {\n \"Date\": \"20200-03-08T00:00:00.000000\",\n  \"type\": \"acctfile\",\n    \"Routing\": \"routing_\"\n  }\n ]\n}"
payload_2 = "{\n    \"ABCD\": [\n  {\n \"Date\": \"TODAY'S_DATE\",\n  \"type\": \"acctfile\",\n    \"Routing\": \"ROUTING_VALUE\"\n  }\n ]\n}"

最终目标是将此有效负载传递到下面的代码段中

url = "https://....."
headers = {'userToken': 'token', 'Content-Type': 'text/plain'}
response = requests.request("POST", url, headers=headers, data=payload, verify=False)
print(response.text)

Tags: texturl路由dateresponsetypecontentrouting
1条回答
网友
1楼 · 发布于 2024-10-03 21:26:55

如果将字符串作为JSON对象加载,那么替换其中的值就很简单了

import datetime
import json

template = "{\n    \"ABCD\": [\n  {\n \"Date\": \"20200-03-08T00:00:00.000000\",\n  \"type\": \"acctfile\",\n    \"Routing\": \"ACCT_1442309\"\n  }\n ]\n}"

o = json.loads(template)

date, routing = datetime.date.today(), 'ABCDEF'

d = o['ABCD'][0]

d['Date'] = date.strftime('%Y-%m-%dT00:00:00.000000')
d['Routing'] = routing

payload = json.dumps(o, indent=4)
print(payload)

相关问题 更多 >