如何将动态数据传递给装饰器 [英] how to pass in dynamic data to decorators

查看:64
本文介绍了如何将动态数据传递给装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个执行以下
的基本crud控制器类:

I am trying to write a base crud controller class that does the following:

class BaseCrudController:
    model = ""
    field_validation = {}
    template_dir = ""

    @expose(self.template_dir)
    def new(self, *args, **kwargs)
        ....

    @validate(self.field_validation, error_handler=new)
    @expose()
    def  post(self, *args, **kwargs):
        ...

我的意图是让控制器扩展此基类,设置
模型,field_validation和模板位置,即可使用。

My intent is to have my controllers extend this base class, set the model, field_validation, and template locations, and am ready to go.

不幸的是,装饰器(据我所知)被解释了当
定义函数时。因此,它无权访问实例的
值。是否可以通过子
类传递动态数据或值?

Unfortunately, decorators (to my understanding), are interpreted when the function is defined. Hence it won't have access to instance's value. Is there a way to pass in dynamic data or values from the sub class?

例如:

class AddressController(BaseCrudController):
    model = Address
    template_dir = "addressbook.templates.addresses"

当我尝试加载AddressController时,它说 self is not defined。我假设基类在子类初始化之前正在评估装饰器。

When I try to load AddressController, it says "self is not defined". I am assuming that the base class is evaluating the decorator before the sub class is initialized.

谢谢,
Steve

Thanks, Steve

推荐答案

也许使用工厂创建类要优于子类化:

Perhaps using a factory to create the class would be better than subclassing:

def CrudControllerFactory(model, field_validation, template_dir):
    class BaseCrudController:
        @expose(template_dir)
        def new(self, *args, **kwargs)
            ....

        @validate(field_validation, error_handler=new)
        @expose()
        def  post(self, *args, **kwargs):
            ....

    return BaseCrudController

这篇关于如何将动态数据传递给装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆