WTForms 不验证类型
WTForms not validating type
我正在尝试使用 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.
需要将数据传递给表单的 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 在评论中指出此 link 以及答案和更多详细信息:WTForms: IntegerField skips coercion on a string value
我正在尝试使用 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.
需要将数据传递给表单的 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 在评论中指出此 link 以及答案和更多详细信息:WTForms: IntegerField skips coercion on a string value