How to pass dynamic data to decorators

I am trying to write a crud controller base 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 intention is for my controllers to extend this base class, set model, field_validation and template locations, and I'm ready to go.

Unfortunately, decorators (as far as I know) are interpreted when a function is defined. Consequently, he will not have access to cost. Is there a way to pass dynamic data or values ​​from a subclass to a class?

For instance:

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

When I try to load the AddressController, it says, "I am not defined." I assume the base class evaluates the decorator before initializing the subclass.

Thanks Steve

+3
source share
2

, factory , :

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
+1

, ( ), , . , . ?

; . :

import functools

def expose(attname=None):
  if attname:
    def makewrapper(f):
      @functools.wraps(f)
      def wrapper(self, *a, **k):
        attvalue = getattr(self, attname, None)
        ...use attvalue as needed...
      return wrapper
    return makewrapper
  else:
    ...same but without the getattr...

, , , Q, expose , ( if attname, wrapper, - . , shoehorning ). , , . , Q " ".

, , , " ", . " ", ! -)

0

Source: https://habr.com/ru/post/1746609/


All Articles