python - 无法在发布方法中发送字典值

标签 python dictionary python-requests

要求:
我必须在请求库中发送字典格式的值来调用发布请求。
r1,r2,r3,r4-返回Success,但是只有r4(手动输入)发送数据。
取得了文档的帮助:https://2.python-requests.org//en/latest/user/quickstart/#more-complicated-post-requests,但是没有运气。
我需要从函数返回值,并在POST请求中发送它们。

Python程序:

import requests, json

url = "https://abccompany.org:8088/services/collector/raw"

headers = {
        'Authorization': 'Splunk 123'
    }

def info():
       userName ="ABC";
       lastActiveDate=123;
       return userName,lastActiveDate


CallingInfo = info()
print("Calling Info :" , CallingInfo , type(CallingInfo))

FinalData = {}
FinalData['userName'] = CallingInfo[0]
FinalData['lastActiveDate'] = CallingInfo[1]
print("FinalData : " , FinalData , type(FinalData))

r1 = requests.post(url, json = FinalData, headers=headers, verify=False)
r2 = requests.post(url, data = json.dumps(FinalData), headers=headers, verify=False)
r3 = requests.post(url, data = FinalData, headers=headers, verify=False)

data = '{"userName": "ABC", "lastActiveDate": 321}'
print("Data : " , data , type(data))
r4 = requests.post(url, headers=headers, data = data, verify=False)

print("Response 1:",r1.text)
print("Response 2:",r2.text)
print("Response 3:",r3.text)
print("Response 4:",r4.text)


输出:

Calling Info : ('ABC', 123) <class 'tuple'>
FinalData :  {'userName': 'ABC', 'lastActiveDate': 123} <class 'dict'>
Data :  {"userName": "ABC", "lastActiveDate": 321} <class 'str'>
Response 1: {"text":"Success","code":0}
Response 2: {"text":"Success","code":0}
Response 3: {"text":"Success","code":0}
Response 4: {"text":"Success","code":0}

最佳答案

在发布请求中,我们无法发送字典或JSON对象,您必须使用请求字典执行json.dumps(data),然后将其发布为url。另一端,您必须执行json.loads。

所以r2和r4应该适合您。

关于python - 无法在发布方法中发送字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59877240/

相关文章:

python - 如何在python中通过正则表达式获取dict值

c++ - 如何更改 map 中的默认整数值?

python - Pygame 中向上转换物的故障排除

python - 如何划分 Pandas 数据框中除特定行以外的所有行?

python - 无法将 postgresql 与 django 连接

python - 从 "non uniform"python 字典中选择随机元素

python - 使用 Python 请求进行 Rest API 身份验证和访问

python - 使用 Python 请求在单个请求中发送文件和 JSON

python - 复杂的上下文菜单子(monad)菜单

python - 如何使用来自另一个字典中匹配键的值更新 YAML 文件?