Pass parameters to a decorator for a class method is to be decorated

decorator, flask, python

Solution

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

Problem

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?

Original source

Related problems