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

定义model

python 复制代码
# @Time      :2024-2024/2/27-14:49
# @Email     :[email protected]
# @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": "[email protected]",
            "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])
相关推荐
一颗知足的心20 分钟前
Go语言之路————接口、泛型
开发语言·golang
沉到海底去吧Go29 分钟前
【图片识别改名】批量读取图片区域文字识别后批量改名,基于Python和腾讯云的实现方案
开发语言·python·腾讯云
MarkHD41 分钟前
第一天 车联网定义、发展历程与生态体系
开发语言·php
百锦再1 小时前
Python深度挖掘:openpyxl和pandas的使用详细
java·开发语言·python·框架·pandas·压力测试·idea
microhex1 小时前
Glide 如何加载远程 Base64 图片
java·开发语言·glide
chilling heart1 小时前
JAVA---集合ArrayList
java·开发语言
Jackilina_Stone1 小时前
【论文阅读/复现】RT-DETR的网络结构/训练/推理/验证/导出模型
论文阅读·python·目标检测·rt-detr
编程自留地1 小时前
第10次:电商项目配置开发环境
python·django·商城
小_t_同学1 小时前
C++之类和对象:构造函数,析构函数,拷贝构造,赋值运算符重载
开发语言·c++
IT技术员1 小时前
【Java学习】动态代理有哪些形式?
java·python·学习