Python3 requests库POST方法如何正确传递嵌套结构的params参数
解决方法
requests 对params的内置编码逻辑会自动拆分嵌套字典:检测到值为字典类型时,会递归拼接键名生成扁平化的查询参数(也就是你看到的一堆json=xxx的效果),不会自动帮你把字典序列化为单个JSON字符串。要实现预期效果,只需要提前把嵌套字典手动序列化为JSON字符串,再作为参数值传入即可。
具体实现调整
- 引入Python标准库
json完成序列化操作 - 替换原本直接传入嵌套字典的写法,提前用
json.dumps()把复合对象转成无多余空格的紧凑JSON字符串 - 其余传参逻辑保持不变,requests会自动对字符串值做URL编码,最终生成的查询串完全匹配接口要求
调整后代码
import requests import json 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 # 提前将嵌套字段序列化为紧凑JSON字符串,去掉默认生成的冗余空格 nested_payload = json.dumps( { '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"] }, separators=(',', ':') ) create(createCustomPayload({ 'entity': 'CustomField', 'json': nested_payload }))
效果验证
运行代码后生成的URL经过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":"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"]}
补充说明:json.dumps()默认会在冒号、逗号分隔符后保留空格,通过separators=(',', ':')参数可以生成和接口要求完全一致的无空格JSON字符串,避免因格式差异导致的解析错误。
内容的提问来源于stack exchange,提问作者sandy
相关产品推荐
相关产品推荐

