front新建forms
forms
如果使用了Email validators 就必须安装email_validator
pip install email_validator
from wtforms import Form, ValidationError
from wtforms.fields import StringField
from wtforms.validators import Email, Length, EqualTo
from models.auth import UserModel
from exts import cache
from flask import request
class RegisterForm(Form):
# 如果使用了Email validators 就必须安装email_validator
email = StringField(validators=[Email(message="请输入正确的邮箱!")])
# 验证码是6位 最大值也是6位
email_captcha = StringField(validators=[Length(6, 6, message="请输入正确格式的邮箱验证码")])
username = StringField(validators=[Length(6, 6, message="请输入正确长度的用户名!")])
password = StringField(validators=[Length(6, 20, message="请输入正确长度的密码")])
repeat_password = StringField(validators=[EqualTo("password", message="两次密码不一致")])
graph_captcha = StringField(validators=[Length(4, 4, message="请输入正确长度的图形验证码")])
# 可以获取email验证其是否存在
def validate_email(self, field):
email = field.data
user = UserModel.query.filter_by(email=email).first()
if user:
raise ValidationError(message='邮箱已经被注册!')
# 获取 email_captcha 会传给field
def validate_email_captcha(self, field):
email_captcha = field.data
email = self.email.data
cache_captcha = cache.get(email)
# 如果缓存中没有取到验证码或者缓存的和输入的不相等
if not cache_captcha or email_captcha != cache_captcha:
raise ValidationError(message='邮箱验证码错误')
def validate_graph_captcha(self, field):
key = request.cookies.get('_graph_captcha_key')
cache_captcha = cache.get(key)
graph_captcha = field.data
if not cache_captcha or cache_captcha.lower() != graph_captcha.lower():
raise ValidationError(message='图形验证码错误')
views
@bp.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template("front/register.html")
else:
form = RegisterForm(request.form)
if form.validate():
pass
else:
print(form.errors)
return 'failure'
@bp.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template("front/register.html")
else:
form = RegisterForm(request.form)
if form.validate():
email = form.email.data
username = form.username.data
password = form.password.data
user = UserModel(email=email,username=username,password=password)
db.session.add(user)
db.session.commit()
return restful.ok()
else:
# form.errors放置了所有的错误信息
# from.errors:{"email":['长度不满足']}
print(form.errors)
return 'failure'
注册报错的格式
class BaseForm(Form):
@property
def messages(self):
message_list = []
if self.errors:
for errors in self.errors.values():
message_list.extend(errors)
return message_list