使用wtforms 实现输入参数自动校验

wtforms

背景

用户注册以及登录是对入参进行校验,一个一个写比较麻烦,使用wtforms模块,类似于前后端一体项目中的表单元素

  1. 继承wtforms 模块的Form类

     from wtforms.fields import *
     from wtforms.validators import *
     from wtforms import Form
     from apps.utils import constant
    
     class Reg(Form):
         # DataRequired 设置是否必填
         user = StringField(validators=[DataRequired(message="no data"),
                                          Length(min=5, max=20, message="error user")])
         # Regexp 入参格式正则匹配
         password = PasswordField(validators=[DataRequired(message="no data"),
                                  Length(min=6, max=20, message="error pwd"),
                                  Regexp(
                                      regex=r"^((?=.*?\d)(?=.*?[a-zA-Z]).{6,20})|((?=.*?\d)(?=.*?[,.;!\[\]()@#$&*_]).{6,20})|"
                                            r"((?=.*?[a-zA-Z])(?=.*?[,.;!\[\]()@#$&*_]).{6,20})",message="not match pwd")])
         # Optional 非必填项,有则校验
         mobile = StringField(validators=[Optional(),
                              Length(min=11, max=11, message="mobile length error"),
                              Regexp(regex=r'^1[35789]\d{9}$', message="mobile error")])
    
         email = StringField(validators=[Optional(),
                             Regexp(regex=r"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$",message="error email")])
    
  2. 视图函数中,对前端输入的body转form,校验,部分代码示例,body体需要先转json

    body = self.request.body
    form = LoginForm.from_json(body)
    if form.validate():
          user = form.user.data
          password = form.password.data
          ......
    else:
          # list, 可能有多个错误
          print(form.errors)
    
posted @ 2020-06-09 14:23  今日店休  阅读(343)  评论(1编辑  收藏  举报