9

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 ?

Community
  • 1
  • 1
jbmusso
  • 3,436
  • 1
  • 25
  • 36
  • 1
    Why is it a method on the class? That will just cause things to break, and it'll only work like a regular function inside the class it was defined in. Unless you're on 3.x, in which case it'll probably work OK. – Devin Jeanpierre Jul 31 '10 at 16:46
  • The decorator is a method on the class because I haven't figured yet how to code a decorator as a class 1/ that accepts argument(s) and 2/ that can access methods to the current class itself. Is this what you meant ? Being mostly self-taught, I'm having trouble fully understanding Bruce Eckell's guide, decorators and inheritance. – jbmusso Jul 31 '10 at 16:57
  • You could just copy-paste the function outside of the class, and it would work fine and normal. Would that be enough to answer your question? – Devin Jeanpierre Jul 31 '10 at 17:18
  • Moving requiredLevel decorator from FoobarController to RequestHandler and decorating it with @staticmethod seems to be the solution according to http://stackoverflow.com/questions/3001138/python-decorators-and-inheritance, however it doesn't do the trick in my situation. Most likely because my decorator accepts parameters ? – jbmusso Jul 31 '10 at 17:26
  • No, I mean removing it from the class altogether. Make it a regular function. – Devin Jeanpierre Jul 31 '10 at 17:55
  • Implemented the decorator as a class in the parent class. Seems to do the work ! See my answer below. Thanks for your input :). – jbmusso Jul 31 '10 at 18:32
  • But *why*? This makes no sense. Do you even realize what I mean? – Devin Jeanpierre Jul 31 '10 at 18:59

2 Answers2

4

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
David Eyk
  • 12,171
  • 11
  • 63
  • 103
1

After digging through StackOverflow, and carefully reading Bruce Eckel's guide to decorators, I think I found a possible solution.

It involves implementing the decorator as a class in the Parent class :

class RequestHandler(webapp.RequestHandler):

    # Decorator class :
    class requiredLevel(object):
        def __init__(self, required_level):
            self.required_level = required_level

        def __call__(self, f):
            def wrapped_f(*f_args):
                if f_args[0].current_user.level >= self.required_level:
                    return f(*f_args)
                else:
                    raise Exception('User has insufficient level to access this resource') 
            return wrapped_f

This does the work ! Using f_args[0] seems a bit dirty to me, I'll edit this answer if I find something prettier.

Then you can decorate methods in subclasses the following way :

FooController(RequestHandler):
    @RequestHandler.requiredLevel(100)
    def get(self, id):
        # Do something here

    @RequestHandler.requiredLevel(250)
    def post(self)
        # Do some stuff here

BarController(RequestHandler):
    @RequestHandler.requiredLevel(500)
    def get(self, id):
        # Do something here

Feel free to comment or propose an enhancement.

jbmusso
  • 3,436
  • 1
  • 25
  • 36
  • you could use `wrapped_f(request_handler, *args, **kwargs)` as the function signature. Also there is no need to put the decorator class into your RequestHandler class. I would put this on module level. – nils Jul 31 '10 at 18:44
  • Thanks for your comment ! I think you just made me understand the way inheritance works differently (and a lot better). I'll update my code accordingly. – jbmusso Jul 31 '10 at 18:53