Flask models

参考资料

用户注册相关模型

from exts import db
from datetime import datetime

# 用户表
class UserModel(db.Model):
    __tablename__ = "User"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(100), nullable=False)   # varchar
    password = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), nullable=False, unique=True)
    join_time = db.Column(db.DateTime, default=datetime.now)

# 验证码表
class EmailCaptchaModel(db.Model):
    __tablename__= "email_captcha"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(100), nullable=False, unique=True)
    captcha = db.Column(db.String(100), nullable=False)
    used = db.Column(db.Boolean, default=False)

用户注册验证表单

import wtforms
from wtforms.validators import Email, Length, EqualTo
from app import db
from models import UserModel, EmailCaptchaModel


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")])

    # 自定义验证:
    # 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="邮箱或验证码错误!")
        else:
            # 可能影响性能
            # 可以用脚本进行替换,例如一周清理一次无效的数据
            db.session.delete(captcha_model)
            db.session.commit()
posted @ 2023-03-06 17:55  默叶  阅读(26)  评论(0编辑  收藏  举报