视图函数在去注册用户之前需要进行验证,表单验证需要先下载 flask-wtf
在终端执行:
pip install flask-wtf
新建forms.py
import wtforms
from wtforms.validators import Email,Length,EqualTo
from models import UserModel,EmailCaptchaModel
# Form:主要就是用来验证前端返回的数据是否符合要求
class RegisterForm(wtforms.Form):
email = wtforms.StringField(validators=[Email(message="邮箱格式错误!")])
captcha = wtforms.StringField(validators=[Length(min=4, max=4, message="验证码格式错误!")])
username = wtforms.StringField(validators=[Length(min=3, max=20, message="用户名格式错误!")])
password = wtforms.StringField(validators=[Length(min=6, max=20, message="密码格式错误!")])
password_confirm = wtforms.StringField(validators=[EqualTo("password", message="两次密码不一致")])
# 自定义验证
# 1.邮箱是否已经被注册
def validate_email(self,field):
email = field.data
user = UserModel.query.filter_by(email=email).first()
if user:
raise wtforms.ValidationError(message="该邮箱已被注册!")
# 2.验证码是否正确
def validate_captcha(self,field):
captcha = field.data
email = self.email.data
captcha_model = EmailCaptchaModel.query.filter_by(email=email,captcha=captcha).first()
if not captcha_model:
raise wtforms.ValidationError(message="邮箱或验证码错误!")
auth.py 代码
注意:
route要加methods参数,不然会报错
request.form 可以拿到前端提交上来的数据
在给数据库增加数据的时候需要给密码加密,防止密码泄露!!
password=generate_password_hash(password)
两种页面跳转方式:
1. return redirect(url_for(“auth.login”))
2. return redirect(“/auth/register1”)
#coding=utf-8
from flask import Blueprint,render_template,jsonify,redirect,url_for
from exts import mail,db
from flask_mail import Message
from flask import request
import string
import random
from models import EmailCaptchaModel,UserModel
from .forms import RegisterForm
from werkzeug.security import generate_password_hash
bp = Blueprint("auth",__name__,url_prefix="/auth")
@bp.route("/register1",methods=['GET', 'POST'])
def regeister():
if request.method == 'GET':
return render_template("register.html")
# 使用requst.form拿到前端提交上来的数据
else:
form = RegisterForm(request.form)
# form.calidate() 方法可以自动的调用表单中的验证器
if form.validate():
email = form.email.data
username = form.username.data
password = form.password.data
user = UserModel(email=email,username=username,password=generate_password_hash(password))
db.session.add(user)
db.session.commit()
return redirect(url_for("auth.login"))
else:
print(form.errors)
return redirect("/auth/register1")