简体   繁体   English

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

[英]Sending a variable as data parameter in requests.post() in Python

I'm trying to pass a variable to the data field in requests.post() and I continue to get the error,我试图将一个变量传递给 requests.post() 中的数据字段,但我继续收到错误消息,

  Error Response: {'error': {'message': 'Exception while reading request', 
'detail': 'Cannod decode: java.io.StringReader@1659711'}, 'status': 'failure'}

Here is my code这是我的代码

#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}')

I originally tried feeding it directly from the CSV using我最初尝试直接从 CSV 使用

str(temp[index][1])

This did not work, so I tried assigning str(temp[index][1]) to the variable serial and then passing the variable like that but that also results in the same error.这不起作用,所以我尝试将str(temp[index][1])分配给变量serial然后像这样传递变量,但这也会导致相同的错误。

A point in the right direction would be great, thanks!指向正确方向的点会很棒,谢谢!

Instead of sending the request payload body in string, pass it in json form.不是以字符串形式发送请求负载正文,而是以 json 形式传递它。 requests.post accepts string in data variable and json in json variable. requests.post 接受数据变量中的字符串和 json 变量中的 json。 I faced a same issue while trying to make my first REST call to ServiceNow instance via Python.我在尝试通过 Python 对 ServiceNow 实例进行第一次 REST 调用时遇到了同样的问题。 Hope this helps.希望这可以帮助。

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

Remove the single quotes from the following :从以下内容中删除单引号:

data='{"asset_tag":"test1", "assigned_to":"test2", 
       "company":"test3", "serial_number":serial}' 

Use

data = {"asset_tag":"test1", "assigned_to":"test2", 
        "company":"test3", "serial_number":serial} 

与其传递 data=data,不如将数据作为 dict 并将其作为 json=data 传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM