login_model.py 816 字节
Newer Older
梦想橡皮擦's avatar
梦想橡皮擦 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
from werkzeug.security import generate_password_hash, check_password_hash

from flask_login import UserMixin
from app import db


class User(UserMixin, db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True)
    password_hash = db.Column(db.String(128))

    @property
    def password(self):
        # 设置密码的属性为只写
        raise AttributeError('密码不能读取')

    @password.setter
    def password(self, password):
        # 当类初始化时自动调用,把 password 的值转换为 hash 值
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password) -> bool:
        # 登录时验证密码
        return check_password_hash(self.password_hash, password)