簡體   English   中英

如何在python3中為請求庫的post方法傳遞嵌套的params對象?

[英]How to pass a nested params object for post method of requests library in python3?

我想創建一個嵌套對象作為參數傳遞給 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"]}

請幫忙。

在我看來,好像您想將'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

為了通過 HTTP 請求將 JSON 對象作為查詢參數發送,您需要先對其進行序列化。

你不會得到你期望的 URL。
相反,您將獲得 JSON 對象的編碼版本,作為查詢參數傳遞。

有關 json 序列化的更多信息,請參見此處

它似乎你試圖從未經授權的來源發送數據,如果網站是 cloudflare 保護,它也可能拋出錯誤..因為我看到你既不使用會話 ID 也不使用 cookie ......這就是為什么你發送正確的數據但它被服務器標記為未經授權請求..如果你需要適當的幫助,請分享網站和有效負載......你也可以使用 request-html 而不是使用請求庫......這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM