简体   繁体   English

python-requests-通过带方括号名称的POST表单发送不起作用

[英]python-requests - Sending via POST form with square brackets names doesn't work

I'm trying to send test[key1] = val1 and test[key2] = val42 to the server via an HTML form. 我正在尝试通过HTML表单将test [key1] = val1和test [key2] = val42发送到服务器。
The corresponding HTML would be: 相应的HTML将是:

<input type="text" name="test[key1]" value="val1" />
<input type="text" name="test[key2]" value="val42" />

(By the way, I would like to know the correct name for this kind of form.) (顺便说一句,我想知道这种形式的正确名称。)

>>> import requests, json
>>> params = { 'test' : { 'key1' : 'val1', 'key2' : 'val42' } }
>>> r = requests.post('http://httpbin.org/post', data=params)
>>> json.loads(r.text)['form']
{u'test': [u'key2', u'key1']}

The post data has been flattened, we get the keys but lost the values val1 and val42 发布数据已被拉平,我们得到了键,但是丢失了值val1和val42

I thought python-requests would handle automatically the params json with embedded keys, that is not the case. 我以为python-requests会自动处理带有嵌入键的params json,事实并非如此。

You need to write params with the square brackets. 您需要使用方括号编写params

>>> params = { 'test[key1]' : 'val1', 'test[key2]' : 'val42' }
>>> r = requests.post('http://httpbin.org/post', data=params)
>>> json.loads(r.text)['form']
{u'test[key1]': u'val1', u'test[key2]': u'val42'}

Hope this will help someone. 希望这会帮助某人。

HTML forms by default cannot be serialized as they don't support nesting. 默认情况下,HTML表单无法序列化,因为它们不支持嵌套。 Use a library like formencode , especially the variabledecode module to serialize/deserialize the form data to json. 使用formencode类的库,尤其是variabledecode模块,可以将表单数据序列化/反序列化为json。

https://github.com/formencode/formencode/blob/master/formencode/variabledecode.py https://github.com/formencode/formencode/blob/master/formencode/variabledecode.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM