gpt4 book ai didi

python - WTForms:IntegerField 跳过对字符串值的强制转换

转载 作者:行者123 更新时间:2023-12-01 05:20:03 25 4
gpt4 key购买 nike

我有一个Form具有单个 IntegerField 的实例.

IntegerField 将 HTML 呈现为 <input>type="text"数据以文本字符串的形式从 HTML 表单 POST 回来。但是,表单不会验证发布的数据是否具有 IntegerField 的字符串值(通过数据参数中的字典传入)。

这是一个玩具示例:

from wtforms import validators, Form, IntegerField 

class TestForm(Form):
num = IntegerField('How Many?', [validators.NumberRange(min=1, max=100)])


test_form1 = TestForm()
print("HTML Render 1: %s" % test_form1.num())

data_in = {'num': '66'} # Note '66' is a string as would be POSTed
test_form2 = TestForm(data=data_in)
print("HTML Render 2: %s" % test_form2.num())
print(" Validate: %s" % test_form2.validate())
print(" Errors: %s" % test_form2.errors)

输出为:

HTML Render 1: <input id="num" name="num" type="text" value="">
HTML Render 2: <input id="num" name="num" type="text" value="66">
Validate: False
Errors: {'num': [u'Number must be between 1 and 100.']}

IntegerField 的文档字符串说:

IntegerField(Field): A text field, except all input is coerced to an integer

我怎样才能强制 str进入int这样这个表单就能通过验证吗?

最佳答案

This来自 WTForms 开发人员之一:

Fields only coerce form data, they don't coerce object data, this lets people use objects >"like an int" and still have them work without the value being clobbered. It's your >responsibility to pass correct datatypes to object/kwargs data.

来自文档:

process_formdata(valuelist) Process data received over the wire from a form.

This will be called during form construction with data supplied through the formdata argument.

Parameter: valuelist – A list of strings to process.

在您的示例中,永远不会调用 IntegerField 上的 process_formdata 方法

您传入的是 str,这不会被强制,因为您将其作为 data 关键字参数提供。 data 关键字参数准确表示您想要在不进行强制的情况下验证的数据。由于 '66' 仍然是 str,验证器不会让它通过。

formdata 关键字参数表示来自网络的数据。这将经历字段的强制过程。只有一个问题,它只接受 MultiDict 之类的对象。如果您看一下下面的示例,我使用了 webob MutliDict,但 Werkzeug 库中也提供了一个。如果您将常规 Python 字典包装在 MultiDict 中,并将其作为 formdata 关键字提供,您的表单将按预期进行验证。

from wtforms import validators, Form, IntegerField 
from webob.multidict import MultiDict

class TestForm(Form):
num = IntegerField('How Many?', [validators.NumberRange(min=1, max=100)])

data_in = {'num': '66'} # Note '66' is a string as would be POSTed
test_form2 = TestForm(formdata=MultiDict(data_in))
print("HTML Render 2: %s" % test_form2.num())
print(" Validate: %s" % test_form2.validate())
print(" Errors: %s" % test_form2.errors)
<小时/>
HTML Render 2: <input id="num" name="num" type="text" value="66">
Validate: True
Errors: {}

关于python - WTForms:IntegerField 跳过对字符串值的强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22585652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com