【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])
相关推荐
2601_9618752417 小时前
法考考试时间安排及科目|时间表|资料已整理
开发语言·c#·inverted-index·suffix-tree·sstable·r-tree·lsm-tree
AI科技星17 小时前
数术工坊第八卷:算力革命
c语言·开发语言·网络·量子计算·agi
geovindu17 小时前
go: Generators Pattern
开发语言·后端·设计模式·golang·生成器模式
茉莉玫瑰花茶18 小时前
综合案例 - AI 智能租房助手 [ 5 ]
服务器·数据库·人工智能·python·ai
文艺倾年18 小时前
【强化学习】强化学习基本概念,20W字总结(一)
人工智能·python·语言模型·自然语言处理·面试·职场和发展·大模型
宸丶一18 小时前
Day 13:持久化记忆 - 让 Agent 拥有长期记忆
jvm·python·ai
码云骑士18 小时前
13-列表append的底层真相(上)-listobject源码中的预分配策略
开发语言·python
浦信仿真大讲堂19 小时前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
xufengzhu19 小时前
第三方 Python 库 Loguru 的进阶实战
python·loguru
.道阻且长.19 小时前
C++ string 操作指南:接口解析
java·c语言·开发语言·c++