3

I am trying to define a decorator in flask which will finally be decorating class methods passing parameters of that class instance. Here is an example what I really want to do.

from functools import wraps
def user_permission(myname):
    def decorator(f):
        @wraps(f)
        def decorated(*args,**argws):
            if myname == 'My Name':
                return f(*args,**argws)
            else:
                return "Not Permitted"
        return decorated
    return decorator

And my manager class is defined as:

class Manager(flask.views.MethodView):

def __init__(self,name):
    self.name = name
@user_permission(self.my_name)
def post(self):
    return "Response"

def get(self):
    return "Response"

What I am trying to do is pass the class variables to the decorator. Yes "self" is not defined at that point but "@decorator.user_permission(self.my_name)" is what I am trying actually because I am yet not solved with my problem.

I couldn't find solution from HERE. Does anybody knows about these stuffs please?

Community
  • 1
  • 1
ln2khanal
  • 949
  • 1
  • 8
  • 16

2 Answers2

6

As you say, self is not defined at that point. This could never work, as a decorator is executed when the class is defined, whereas you want something to run when the instance method is called.

However I think you're really overcomplicating this. self is passed to the method itself. So there's no reason to try and make it a parameter to the decorator, since the decorator has access to the method arguments. This would be much simpler:

from functools import wraps
def user_permission():
    @wraps(f)
    def decorated(self, *args, **kwargs):
        if self.myname == 'My Name':
            return f(self, *args, **kwargs)
        else:
            return "Not Permitted"
    return decorated
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

self is just an argument. You don't need a decorator factory.

def user_permission(f):
    @wraps(f)
    def decorated(self, *args, **kw):
        if self.myname == 'My Name':
            return f(self, *args, **kw)
        else:
            return "Not Permitted"

    return decorated
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124