如何在python3中为请求库的post方法传递嵌套的params对象?

2024-04-26 04:35:09 发布

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

我想创建一个嵌套对象作为参数传递给requests.post方法。 这是我的密码-

import requests

baseURL = "http://ec2-3-6-40-236.ap-south-1.compute.amazonaws.com/civicrm/sites/all/modules/civicrm/extern/rest.php?"
userkey = "secret"
sitekey = "secret"


def create(payload):
    r = requests.post(baseURL, params=payload)
    print(r.url)


def createCustomPayload(customPayload):
    payloadCommon = {'action': 'create', 'api_key': userkey, 'key': sitekey}
    payloadCommon.update(customPayload)
    return payloadCommon


create(createCustomPayload({'entity': 'CustomField', 'json': {'custom_group_id': 'test_16Nov_Voter', 'label': 'Relationship With Guardian',
                                                              'data_type': 'String', 'html_type': 'Radio', 'weight': 7, 'options_per_line': 2, 'option_values': ["Father", "Mother", "Husband", "Other"]}}))

它打印这个URL-

http://ec2-3-6-40-236.ap-south-1.compute.amazonaws.com/civicrm/sites/all/modules/civicrm/extern/rest.php?action=create&api_key=secret&key=secret&entity=CustomField&json=custom_group_id&json=label&json=data_type&json=html_type&json=weight&json=options_per_line&json=option_values

理想情况下,它应该打印此URL-

http://ec2-3-6-40-236.ap-south-1.compute.amazonaws.com/civicrm/sites/all/modules/civicrm/extern/rest.php?entity=CustomField&action=create&api_key=secret&key=secret&json={"custom_group_id":"test_16Nov_Voter","label":"Relationship With Guardian","options_per_line":2,"data_type":"String","html_type":"Radio","weight":7,"option_values":["Father","Mother","Husband","Other"]}

请帮忙


Tags: keycomjsonhttpsecrettypecreateec2
1条回答
网友
1楼 · 发布于 2024-04-26 04:35:09

它似乎在试图从未经授权的来源发送数据,如果网站是cloudflare protect,也可能会抛出错误。正如我看到的,你既不使用会话id也不使用cookie。。。这就是为什么你发送正确的数据,但它被服务器标记为未经授权的请求。。如果您需要适当的帮助,请共享网站和负载…您也可以使用请求html而不是使用请求库。。。 Here

网友
2楼 · 发布于 2024-04-26 04:35:09

在我看来,您似乎希望将'json'键下的对象作为json字符串传递:

def createCustomPayload(customPayload):
    import json
    if "json" in customPayload:
        # convert the object into a json string and attach under the json key
        customPayload["json"] = json.dumps(customPayload["json"])
    
    payloadCommon = {'action': 'create', 'api_key': userkey, 'key': sitekey}
    payloadCommon.update(customPayload)

    return payloadCommon
网友
3楼 · 发布于 2024-04-26 04:35:09

为了通过HTTP请求将JSON对象作为查询参数发送,需要首先对其进行序列化

您将无法获得预期的URL。
相反,您将获得JSON对象的编码版本,作为查询参数传递

有关json序列化的更多信息,请参见here

相关问题 更多 >