Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass in dynamic data to decorators

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):
        ...

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?

For example:

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

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.

Thanks, Steve

like image 720
steve Avatar asked Jan 27 '26 15:01

steve


1 Answers

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
like image 56
Andrew E. Falcon Avatar answered Jan 29 '26 05:01

Andrew E. Falcon