gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:50:23 25 4
gpt4 key购买 nike

要求:
我必须在请求库中发送字典格式的值来调用发布请求。
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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com