views:

254

answers:

2

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 ?

A: 

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.

Sorw
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
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.
Sorw
+1  A: 

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