【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])
相关推荐
YuanDaima2048几秒前
基于 LangChain 1.0 的检索增强生成(RAG)实战
人工智能·笔记·python·langchain·个人开发·langgraph
无巧不成书02187 分钟前
C语言零基础速通指南 | 1小时从入门到跑通完整项目
c语言·开发语言·编程实战·c语言入门·零基础编程·c语言速通
三雷科技22 分钟前
使用 `dlopen` 动态加载 `.so` 文件
开发语言·c++·算法
wellc35 分钟前
java进阶知识点
java·开发语言
RopenYuan36 分钟前
FastAPI -API Router的应用
前端·网络·python
听风吹等浪起38 分钟前
用Python和Pygame从零实现坦克大战
开发语言·python·pygame
灰色小旋风39 分钟前
力扣合并K个升序链表C++
java·开发语言
_MyFavorite_42 分钟前
JAVA重点基础、进阶知识及易错点总结(28)接口默认方法与静态方法
java·开发语言·windows
取码网1 小时前
最新在线留言板系统PHP源码
开发语言·php
环黄金线HHJX.1 小时前
龙虾钳足启发的AI集群语言交互新范式
开发语言·人工智能·算法·编辑器·交互