在flask.request.form中的动态表单字段 [英] Dynamic form fields in flask.request.form

查看:2341
本文介绍了在flask.request.form中的动态表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经查看了文档,但是对于我来说,我无法弄清楚Flask中的 request.form 对象是如何被填充的。 文档说,它充满了POST或PUT请求的解析表单数据,但是我的表单是动态的,所以我不一定知道发送POST请求时存在哪些字段 - 尽管我想确保将这些字段的信息添加到数据库中。



表单中的某些字段总是在那里,但是从约60列表中还会有任何额外的字段。我应该如何去确定请求中的哪些附加字段,以及如何得到来自他们的数据?

编辑:我的具体问题已经解决,但它仍然值得问如何填充request.form字典。我发现,如果一个复选框的输入没有被选中,就没有任何关键字被添加到它的名字下面的字典中,并且试图从字典中得到一个不存在的关键字的值会导致一个相当混乱和含糊的 HTTP 400 BAD REQUEST 错误。

解决方案

request .form 返回一个 MultiDict 对象。基本上,这意味着对于1个键,您可以有多个值。如果你想测试你的表单POST的样子,只需要做一个快速的打印语句,如下所示:

  f = request.form 
为f.keys()中的键值:
为f.getlist(key)中的值:
打印键,:,值

如果您阅读MultiDict的文档,它说

MultiDict是定制的字典子类来处理同一个键的多个值,例如在包装器中的解析函数中使用这是必要的,因为一些HTML表单元素为同一个键传递多个值。

http://werkzeug.pocoo.org/docs/ datastructures /#werkzeug.datastructures.MultiDict


I've looked through the documentation, but for the life of me, I can't figure out how the request.form object in Flask is populated. The documentation says that it's filled with parsed form data from POST or PUT requests, but my form is dynamic so I don't necessarily know what fields exist when the POST request is sent - though I want to make sure I add the information from these fields to the database.

Some of the fields in the form are always there, but there will also be any number of extra fields from a list of about 60. How should I go about figuring out which of these additional fields are in the request and how should I get the data from them?

EDIT: My specific problem has been solved, but it's still worth asking how the request.form dictionary is populated. I found out the hard way that if a checkbox input is unchecked, there is no key added to the dictionary under its name, and trying to get the value of a key that does not exist from the dictionary results in a rather confusing and cryptic HTTP 400 BAD REQUEST error.

解决方案

request.form returns a MultiDict object. Basically, it means that for 1 key, you could have multiple values. If you want to test what your form POST looks like, just do a quick print statement as follows

f = request.form
for key in f.keys():
    for value in f.getlist(key):
        print key,":",value

If you read the documentation for MultiDict, it says

"A MultiDict is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers. This is necessary because some HTML form elements pass multiple values for the same key."

http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict

这篇关于在flask.request.form中的动态表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆