在 Python 中的 requests.post() 中发送变量作为数据参数

-1 python post python-requests servicenow servicenow-rest-api

我试图将变量传递到 requests.post() 中的数据字段,但我继续收到错误,

  Error Response: {'error': {'message': 'Exception while reading request', 
'detail': 'Cannod decode: java.io.StringReader@1659711'}, 'status': 'failure'}
Run Code Online (Sandbox Code Playgroud)

这是我的代码

#Fill array from CSV
temp=[]
for row in csv.iterrows():
    index, data = row
    temp.append(data.tolist())


#Create new asset for all assets in CSV
for index, row in enumerate(temp):
    make = temp[index][0]
    serial = str(temp[index][1])
    date = str(temp[index][2])
    response = requests.post(url, auth=(user, pwd), headers=headers, 
    data='{"asset_tag":"test1", "assigned_to":"test2", 
    "company":"test3", "serial_number":serial}')
Run Code Online (Sandbox Code Playgroud)

我最初尝试使用直接从 CSV 提供数据

str(temp[index][1])
Run Code Online (Sandbox Code Playgroud)

这不起作用,所以我尝试分配str(temp[index][1])给变量serial,然后像这样传递变量,但这也会导致相同的错误。

如果能找到正确的方向就太好了,谢谢!

Mil*_*ale 5

不要以字符串形式发送请求有效负载正文,而是以 json 形式传递。requests.post 接受 data 变量中的字符串和 json 变量中的 json。我在尝试通过 Python 对 ServiceNow 实例进行第一次 REST 调用时遇到了同样的问题。希望这可以帮助。

response = requests.post(url, auth=(user, pwd), headers=headers, 
    json={"asset_tag":"test1", "assigned_to":"test2", 
    "company":"test3", "serial_number":serial})
Run Code Online (Sandbox Code Playgroud)