wtforms表单框架

1.安装

pip install WTForms

2.关键概念

·Forms是WTForms库的核心容器,它包含一系列的Fields,可通过属性或字典样式访问;

·Fields是最主要的表单处理单元,每一种表单数据类型对应着一种Field,Filed还包含一些有用的属性,如:标签、描述信息、验证错误信息等;

·每一个Field都有一个Widget实例,用于生成该Field的HTML元素;

·Field还包含一个Validators列表,用于指定该字段的验证规则。

3.使用示例

base.py

from wtforms import Form
from flask import request

from app.abnormal.error_code import ParameterException


class BaseForm(Form):
    def __init__(self):
        data = request.json
        super(BaseForm, self).__init__(data=data)

    def validate_for_api(self) -> object:
        valid = super(BaseForm, self).validate()
        if not valid:
            raise ParameterException(msg=self.errors)
        return self

forms.py

#扩展表单项示例

from wtforms import StringField, IntegerField, DateTimeField, FieldList, DateField, FormField, FloatField
from wtforms import Form as WTForm
from wtforms.validators import DataRequired, Email, NumberRange
from app.validators.base import BaseForm as Form


class TaskOderlListIn(WTForm):
    order_id = IntegerField(validators=[])  # 订单id


class QueryIn(Form):
    type = StringField(validators=[])
    status = IntegerField(validators=[])
    sale_price = FloatField()
    start_date = DateTimeField(validators=[DataRequired()])
    start_product_valid_term = DateField(validators=[])
    order_list = FieldList(FormField(TaskOderlListIn))  # 订单列表
    order_state = FieldList(IntegerField(validators=[])) 

create.py

#在视图函数中使用表单

@api.route(‘/create‘, methods=[‘POST‘])
@auth.login_required
def create_channel():
    form = QueryIn().validate_for_api()

    type = form.type.data
    status = form.status.data
    sale_price = form.sale_price.data
    start_product_valid_term = form.start_product_valid_term.data
    order_list = form.order_list.data
    order_state = form.order_state.data

    for item in order_list:
        order_id = item.order_id.data

4.常用Validators

conn_type = IntegerField(validators=[DataRequired(message=None), NumberRange(min=1, max=2, message=None)])

说明
DataRequired(message=None) field值必须传递
Email(message=None) field值是否为email地址
EqualTo(fieldname, message=None) field的值是否与fieldname对应field的值相同
InputRequired(message=None) 验证用户是否输入了内容
IPAddress(ipv4=True, ipv6=False, message=None) 验证是否为IP地址
Length(min=-1, max=-1, message=None) 验证输入的字符串长度是否在指定范围内
MacAddress(message=None) 验证是否为MAC地址
NumberRange(min=None, max=None, message=None) 验证数值是否在指定范围内
Optional(strip_whitespace=True) 指定当前field为可选,停止对其进行验证
Regexp(regex, flags=0, message=None) 使用正则表达式验证当前field
URL(require_tld=True, message=None) 验证是否为URL地址
UUID(message=None) 验证是否为UUID字符串
AnyOf(values, message=None, values_formatter=None) 验证输入值是否为values之一
NoneOf(values, message=None, values_formatter=None) 验证输入值是否不是values中任何一个

5.自定义validators

custom_validators.py

from wtforms import ValidationError


class Length(object):
    def __init__(self, min=-1, max=-1, message=None):
        # 定义validator初始化输入
        self.min = min
        self.max = max
        if not message:
            message = u‘Field must be between %i and %i characters long.‘ % (min, max)
        self.message = message

    def __call__(self, form, field):
        l = field.data and len(field.data) or 0
        if l < self.min or self.max != -1 and l > self.max:
            raise ValidationError(self.message)

forms.py

from wtforms import StringField
from wtforms import Form as WTForm
from wtforms.validators import DataRequired, Email, NumberRange
from app.validators.base import BaseForm as Form
from app.validators.custom_validators import Length

class MyForm(Form):
    # 4. 使用自定义validator  Length
    name = StringField(‘Name‘, [InputRequired(), Length(max=50)])  

wtforms表单框架

上一篇:vb 无效的属性值,运行时错误380


下一篇:Map实用