【flask+python】利用魔术方法,更优雅的封装model类

定义model

python 复制代码
# @Time      :2024-2024/2/27-14:49
# @Email     :514422868@qq.com
# @Author    :Justin
# @file      :user.py
# @Software  :01-fishbook
from app.model.base import Base
from sqlalchemy import Column, Integer, SmallInteger, String
from werkzeug.security import generate_password_hash, check_password_hash


class User(Base):
    # auto_increment=True 不需要auto_increment
    id = Column(Integer, primary_key=True)
    nickname = Column(String(32), index=True, nullable=False, unique=True)
    email = Column(String(32), index=True, nullable=False, unique=True)
    status = Column(SmallInteger, default=1)
    _password = Column("password", String(256))

    @property
    def password(self):
        return self._password

    # 这里必须是属性名称
    @password.setter
    def password(self, raw):
        self._password = generate_password_hash(raw)

    def check_password(self, raw: str):
        # 必须是先是加密之后的密码,再是原始密码
        return check_password_hash(self.password, raw)

里面的注释要好好看,

注意@property是 obj.password时触发,因为password是密文存储的,

所以,在赋值时指向password(self,raw)的方法,将它加密

使用的generate_password_hash 和 check_password_hash 都是werkzeug.security下的方法。

因为两个魔力函数的存在,使得,

涉及密码时不可以传统的方式验证用户是否存在:

python 复制代码
def find_user():
    with app.app_context():
        # 上面一种查询方式错误,因为对password的属性进行了getter和setter的装饰器修饰
        # User.query.filter_by(email=email, password=password).first()
        # 正确的方式应用这样
        # user = User.query.filter_by(_password="123456").first()
        # 业务上的使用方式是这样:
        param = {
            "email": "a@qq.com",
            "password": "123456"
        }
        user = User.query.filter_by(email=param["email"]).first()
        if user:
            print(user.check_password(param["password"]))
        print(user)
        a_en = generate_password_hash("a")
        print(check_password_hash(a_en, "a"))
        print(a_en)

filter的妙用

python 复制代码
	@property
    def intro(self):
        self.intro = filter(lambda x: True if x else False, [self.author, self.publisher, self.price])
相关推荐
_OP_CHEN1 小时前
C++基础:(十二)list类的基础使用
开发语言·数据结构·c++·stl·list类·list核心接口·list底层原理
Bellafu6662 小时前
selenium常用的等待有哪些?
python·selenium·测试工具
小白学大数据3 小时前
Python爬虫常见陷阱:Ajax动态生成内容的URL去重与数据拼接
爬虫·python·ajax
2401_841495644 小时前
【计算机视觉】基于复杂环境下的车牌识别
人工智能·python·算法·计算机视觉·去噪·车牌识别·字符识别
Adorable老犀牛4 小时前
阿里云-ECS实例信息统计并发送统计报告到企业微信
python·阿里云·云计算·企业微信
ONE_PUNCH_Ge4 小时前
Go 语言变量
开发语言
幼稚园的山代王4 小时前
go语言了解
开发语言·后端·golang
倔强青铜三4 小时前
苦练Python第66天:文件操作终极武器!shutil模块完全指南
人工智能·python·面试
倔强青铜三4 小时前
苦练Python第65天:CPU密集型任务救星!多进程multiprocessing模块实战解析,攻破GIL限制!
人工智能·python·面试
晚风残4 小时前
【C++ Primer】第六章:函数
开发语言·c++·算法·c++ primer