我尝试使用wtforms
检查字典中的数据是否属于所需类型。在下面的示例中,我想确保字典中的some_field
是整数。该文档让我相信,如果我使用IntegerField
,数据将被强制转换为整数,StringField
将强制转换为字符串等。但是,foo.validate()
正在返回True
即使some_field
的类型不是整数。这是预期的行为,为什么?如果是预期的行为,是否可以根据需要使用wtforms
进行类型验证?
>>> from wtforms import Form, IntegerField, validators
>>> class Foo(Form):
... some_field = IntegerField(validators=[validators.Required()])
>>> foo = Foo(**{'some_field':'some text input'})
>>> foo.data
{'some_field': 'some text input'}
>>> foo.validate()
True
>>> IntegerField?
Type: type
String form: <class 'wtforms.fields.core.IntegerField'>
File: c:\users\appdata\local\continuum\anaconda\envs\env\lib\site-packages\wtforms\fields\core.py
Init definition: IntegerField(self, label=None, validators=None, **kwargs)
Docstring:
A text field, except all input is coerced to an integer. Erroneous input
is ignored and will not be accepted as a value.
答案 0 :(得分:0)
需要将数据传递给表单formdata
参数,以强制进行类型强制。要将数据传递到formdata
,请使用MultiDict
。
In [2]: from wtforms import Form, IntegerField, validators
In [3]: class Foo(Form):
...: some_field = IntegerField(validators=[validators.Required()])
In [4]: from werkzeug.datastructures import MultiDict
In [5]: foo = Foo(formdata=MultiDict({'some_field':'some text input'}))
In [6]: foo.data
Out[6]: {'some_field': None}
In [7]: foo.validate()
Out[7]: False
感谢Max在评论中指出了这个链接的答案和更多细节:WTForms: IntegerField skips coercion on a string value