使用 RaiseExceptionMeta 元类隐式装饰 Validator 类中的所有校验方法

简介: 使用 RaiseExceptionMeta 元类隐式装饰 Validator 类中的所有校验方法

一、前置说明


1、本节目标

  • 了解元类 metaclass 的使用。
  • 了解 __new__ 方法的使用。
  • 了解如何使用元类隐式装饰类中的所有方法。


2、相关回顾


二、操作步骤


1、项目目录


  • atme : @me 用于存放临时的代码片断或其它内容。
  • pyparamvalidate : 新建一个与项目名称同名的package,为了方便发布至 pypi 。
  • core : 用于存放核心代码。
  • tests : 用于存放测试代码。
  • utils : 用于存放一些工具类或方法。


2、代码实现

atme/demo/validator_v3/validator.py

import functools
import inspect
def _error_prompt(value, exception_msg=None, rule_des=None, field=None):
    """
    优先使用校验方法中的错误提示, 如果方法中没有错误提示,则使用"字段规则描述"代替错误提示
    拼接出:name error: "123" is invalid. due to: name must be string.
    """
    default = f'"{value}" is invalid.'
    prompt = exception_msg or rule_des
    prompt = f'{default} due to: {prompt}' if prompt else default
    prompt = f'{field} error: {prompt}' if field else prompt
    return prompt
def raise_exception(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        bound_args = inspect.signature(func).bind(self, *args, **kwargs).arguments
        exception_msg = kwargs.get('exception_msg', None) or bound_args.get('exception_msg', None)
        error_prompt = _error_prompt(self.value, exception_msg, self._rule_des, self._field)
        result = func(self, *args, **kwargs)
        if not result:
            raise ValueError(error_prompt)
        return self
    return wrapper
class RaiseExceptionMeta(type):
    def __new__(cls, name, bases, dct):
        for key, value in dct.items():
            # 如果是静态方法,则将它替换为一个新的静态方法,新的静态方法调用 raise_exception 函数,将原静态方法作为参数传递给raise_exception
            if isinstance(value, staticmethod):
                dct[key] = staticmethod(raise_exception(value.__func__))
            # 如果是类方法,则将它替换为一个新的类方法,新的类方法调用 raise_exception 函数,将原类方法作为参数传递给raise_exception
            if isinstance(value, classmethod):
                dct[key] = classmethod(raise_exception(value.__func__))
            # 如果是普通的成员方法,则将它替换为一个新的函数,新函数调用 raise_exception 函数,将原函数作为参数传递给 raise_exception
            # 排除掉以双下划线 __ 开头的方法, 如 __init__,__new__等
            if inspect.isfunction(value) and not key.startswith("__"):
                dct[key] = raise_exception(value)
        return super().__new__(cls, name, bases, dct)
class Validator(metaclass=RaiseExceptionMeta):
    def __init__(self, value, field=None, rule_des=None):
        """
        :param value: 待校验的值
        :param field: 校验字段
            - 用于提示具体哪个字段错误
            - 如 'name error: name must be string'
            - error 前面的 `name` 即为 field
        :param rule_des: 校验规则描述
        """
        self.value = value
        self._field = field
        self._rule_des = rule_des
    def is_string(self, exception_msg=None):
        return isinstance(self.value, str)
    def is_not_empty(self, exception_msg=None):
        return bool(self.value)


3、测试代码

atme/demo/validator_v3/test_validator.py

import pytest
from atme.demo.validator_v3.validator import Validator
def test_validator_01():
    """
    在 Validator 实例化时,不给 field、rule_des 传值; 在校验方法中,不给 exception_msg 传值
    """
    validator = Validator('Jane')
    assert validator.is_string().is_not_empty()
    with pytest.raises(ValueError) as exc_info:
        validator = Validator(123)
        validator.is_string().is_not_empty()
    assert 'invalid' in str(exc_info.value)
    print(exc_info.value)  # 输出: "123" is invalid.
def test_validator_02():
    """
    在 Validator 实例化时,给 field、rule_des 传值
    """
    validator = Validator('Jane', field='name', rule_des='name must be string from rule des.')
    assert validator.is_string().is_not_empty()
    with pytest.raises(ValueError) as exc_info:
        validator = Validator(123, field='name', rule_des='name must be string from rule des.')
        validator.is_string().is_not_empty()
    assert 'name must be string from rule des.' in str(exc_info.value)
    print(exc_info.value)  # 输出: name error: "123" is invalid. due to: name must be string from rule des.
def test_validator_03():
    """
    在 Validator 实例化时,给 field、rule_des 传值; 在校验方法中,给 exception_msg 传值
    """
    validator = Validator('Jane', field='name', rule_des='name must be string from rule des.')
    assert validator.is_string().is_not_empty()
    with pytest.raises(ValueError) as exc_info:
        validator = Validator(123, field='name', rule_des='name must be string from rule des.')
        validator.is_string('name must be string from method exception msg.').is_not_empty()
    assert 'name must be string from method exception msg.' in str(exc_info.value)
    print(exc_info.value)  # 输出: "123" is invalid due to "name error: name must be string from method exception msg."
def test_validator_04():
    """
    field_name 为空
    """
    validator = Validator('Jane', rule_des='name must be string from rule des.')
    assert validator.is_string().is_not_empty()
    with pytest.raises(ValueError) as exc_info:
        validator = Validator(123, rule_des='name must be string from rule des.')
        validator.is_string('name must be string from method exception msg.').is_not_empty()
    assert 'name must be string from method exception msg.' in str(exc_info.value)
    print(exc_info.value)  # 输出: "123" is invalid due to "name must be string from method exception msg."


4、日志输出

执行 test 的日志如下,验证通过:

============================= test session starts =============================
collecting ... collected 4 items
test_validator.py::test_validator_01 PASSED                              [ 25%]"123" is invalid.
test_validator.py::test_validator_02 PASSED                              [ 50%]name error: "123" is invalid. due to: name must be string from rule des.
test_validator.py::test_validator_03 PASSED                              [ 75%]name error: "123" is invalid. due to: name must be string from method exception msg.
test_validator.py::test_validator_04 PASSED                              [100%]"123" is invalid. due to: name must be string from method exception msg.
============================== 4 passed in 0.01s ==============================


三、后置说明


1、要点小结

  • 元类 metaclass 可以控制类的创建过程,可以动态的修改类的属性、方法和其他行为;
  • __new__ 用于创建实例,__init__ 用于初始化实例。
  • 在 RaiseExceptionMeta 类中,它会遍历类的字典(包括属性和方法),并对其中的静态方法、类方法和普通成员方法进行修改。
  • 经过优化后,虽然从功能上实现了链式调用的效果,但由于校验方法没有 return self , 编辑器如 pycharm 不能智能识别可链式调用的方法(如下图),对用户很不友好,需要继续优化。


2、下节准备

  • 使用 TypeVar 创建 Self 类变量,方便用户在 pycharm 编辑器中进行链式调用

点击进入《Python装饰器从入门到进阶》总目录

目录
相关文章
|
机器学习/深度学习 数据采集 测试技术
Dowhy,一个强大的Python库,做金融量化领域的可以尝试下!
Dowhy,一个强大的Python库,做金融量化领域的可以尝试下!
928 2
|
存储 数据采集 数据挖掘
质量追溯系统方案
质量追溯系统方案
1196 1
|
开发框架 监控 安全
webshell检测方法归纳
webshell检测方法归纳
1468 0
|
SQL 关系型数据库 MySQL
MySQL技能完整学习列表3、SQL语言基础——1、SQL(Structured Query Language)简介——2、基本SQL语句:SELECT、INSERT、UPDATE、DELETE
MySQL技能完整学习列表3、SQL语言基础——1、SQL(Structured Query Language)简介——2、基本SQL语句:SELECT、INSERT、UPDATE、DELETE
642 0
|
12月前
|
SQL BI 测试技术
浙江头部城商行:每日 700 万查询、秒级响应,Apache Doris 查算分离架构破局资源冲突
在当前银行业务全面线上化、实时化的驱动下,浙江省头部城商行亟需构建一个能够同时承载海量数据加工与高并发实时查询的数据平台,以支撑精准营销、实时风控和智能决策等关键业务。 在这一数字化转型进程中,我们最终引入了 Apache Doris 作为湖仓一体架构的核心组件。Doris 凭借其卓越的查询性能、高吞吐、对标准 SQL 的完整支持以及高效的实时数据摄入能力,在多个候选方案中脱颖而出。尤其值得一提的是,其架构的灵活度及可扩展性、极大降低了运维难度和成本投入。截至目前,我们已顺利完成 200TB+ 历史数据的平滑迁移与落地,为后续的深度应用奠定了坚实基础。
552 0
浙江头部城商行:每日 700 万查询、秒级响应,Apache Doris 查算分离架构破局资源冲突
|
自然语言处理 数据可视化 数据挖掘
提升效率必看:从0到1的看板工具任务分组方法全解析
本文系统介绍看板任务分组方法,通过可视化工作流、限制在制品、优化流动与持续改进,提升团队协作效率。结合多项目管理、客户服务等场景,详解如何按项目、优先级、负责人等维度分组,并以板栗看板为例演示实操步骤,辅以Python自动化技巧与Q&A,助力团队实现高效、灵活的任务管理。
|
存储 C# 图形学
Unity 逐字显示 打字机效果
在 Unity 中实现逐字显示的打字机效果,主要通过 UGUI Text 组件和 C# 脚本完成。核心原理是将文本逐字拆分并按时间间隔依次显示。具体步骤如下:1. 创建 Text 组件和脚本;2. 使用协程或 Update 方法控制字符逐个显示。代码示例展示了两种实现方式,一种使用协程 `IEnumerator`,另一种通过 `Update` 方法结合 `Substring` 实现逐字显示效果。
|
存储 安全 API
从零开始认识 API,可以从哪几个方面入手
API(应用程序编程接口)是软件组件间通信的桥梁,通过预定义的函数、规则或协议实现数据和功能的交换。API 的工作原理是客户端向服务器发送请求,服务器处理后返回响应。其主要作用包括提高开发效率、促进软件的可扩展性和可维护性、实现数据共享和系统集成。API 类型多样,包括数据 API、操作系统 API、远程 API 和网络 API 等。使用 API 时需查阅官方文档、使用开发工具和抓包工具,并注意认证与授权、输入验证和数据加密等安全事项。
|
JSON 安全 API
CMS识别
【10月更文挑战第03天】
568 6
|
数据采集 Web App开发 存储
基于Python的51job(前程无忧)招聘网站数据采集,通过selenium绕过网站反爬,可以采集全国各地数十万条招聘信息
本文介绍了一个使用Python和Selenium库实现的51job(前程无忧)招聘网站数据采集工具,该工具能够绕过网站的反爬机制,自动化登录、搜索并采集全国各地的招聘信息,将数据保存至CSV文件中。
1559 1