Search code examples
pythonweb-applicationsdecoratorsubclassing

Python decorators and class inheritance


I'm trying to use decorators in order to manage the way users may or may not access resources within a web application (running on Google App Engine). Please note that I'm not allowing users to log in with their Google accounts, so setting specific access rights to specific routes within app.yaml is not an option.

I used the following resources :
- Bruce Eckel's guide to decorators
- SO : get-class-in-python-decorator2
- SO : python-decorators-and-inheritance
- SO : get-class-in-python-decorator

However I'm still a bit confused...

Here's my code ! In the following example, current_user is a @property method which belong to the RequestHandler class. It returns a User(db.model) object stored in the datastore, with a level IntProperty().

class FoobarController(RequestHandler):

    # Access decorator
    def requiredLevel(required_level):
        def wrap(func):
            def f(self, *args):
                if self.current_user.level >= required_level:
                    func(self, *args)
                else:
                    raise Exception('Insufficient level to access this resource') 
            return f
        return wrap

    @requiredLevel(100)
    def get(self, someparameters):
        #do stuff here...

    @requiredLevel(200)
    def post(self):
        #do something else here...

However, my application uses different controllers for different kind of resources. In order to use the @requiredLevel decorator within all subclasses, I need to move it to the parent class (RequestHandler) :

class RequestHandler(webapp.RequestHandler):

    #Access decorator
    def requiredLevel(required_level):
        #See code above

My idea is to access the decorator in all controller subclasses using the following code :

class FoobarController(RequestHandler):

    @RequestHandler.requiredLevel(100)
    def get(self):
        #do stuff here...

I think I just reached the limit of my knowledge about decorators and class inheritance :). Any thoughts ?


Solution

  • Your original code, with two small tweaks, should also work. A class-based approach seems rather heavy-weight for such a simple decorator:

    class RequestHandler(webapp.RequestHandler):
    
        # The decorator is now a class method.
        @classmethod     # Note the 'klass' argument, similar to 'self' on an instance method
        def requiredLevel(klass, required_level):
            def wrap(func):
                def f(self, *args):
                    if self.current_user.level >= required_level:
                        func(self, *args)
                    else:
                        raise Exception('Insufficient level to access this resource') 
                return f
            return wrap
    
    
    class FoobarController(RequestHandler):
        @RequestHandler.requiredLevel(100)
        def get(self, someparameters):
            #do stuff here...
    
        @RequestHandler.requiredLevel(200)
        def post(self):
            #do something else here...
    

    Alternately, you could use a @staticmethod instead:

    class RequestHandler(webapp.RequestHandler):
    
        # The decorator is now a static method.
        @staticmethod     # No default argument required...
        def requiredLevel(required_level):
    

    The reason the original code didn't work is that requiredLevel was assumed to be an instance method, which isn't going to be available at class-declaration time (when you were decorating the other methods), nor will it be available from the class object (putting the decorator on your RequestHandler base class is an excellent idea, and the resulting decorator call is nicely self-documenting).

    You might be interested to read the documentation about @classmethod and @staticmethod.

    Also, a little bit of boilerplate I like to put in my decorators:

        @staticmethod
        def requiredLevel(required_level):
            def wrap(func):
                def f(self, *args):
                    if self.current_user.level >= required_level:
                        func(self, *args)
                    else:
                        raise Exception('Insufficient level to access this resource') 
                # This will maintain the function name and documentation of the wrapped function.
                # Very helpful when debugging or checking the docs from the python shell:
                wrap.__doc__ = f.__doc__
                wrap.__name__ = f.__name__
                return f
            return wrap