I am trying to re-use a member function decorator for other member function decorator but I am getting the following error:
'function' object has no attribute '_MyClass__check_for_valid_token'
Basically I have a working decorator that checks if a user is logged in (@LOGIN_REQUIRED
) and I would like to call this first in the @ADMIN_REQUIRED
decorator (so the idea is to check that the user is logged in with the existing @LOGIN_REQUIRED
decorator and then add some specific validation to check if the logged user is an Administrator in the @ADMIN_REQUIRED
decorator.
My current code is like this:
class MyClass:
def LOGIN_REQUIRED(func):
@wraps(func)
def decorated_function(self, *args, **kwargs):
# username and token should be the first parameters
# throws if not logged in
self.__check_for_valid_token(args[0], args[1])
return func(self, *args, **kwargs)
return decorated_function
@LOGIN_REQUIRED
def ADMIN_REQUIRED(func):
@wraps(func)
def decorated_function(self, *args, **kwargs):
is_admin = self.check_if_admin()
if not is_admin:
raise Exception()
return func(self, *args, **kwargs)
return decorated_function
@ADMIN_REQUIRED
def get_administration_data(self, username, token):
# return important_data
# currently throws 'function' object has no attribute '_MyClass__check_for_valid_token'
Do you have any idea how could I get this to work?
Some notes based on the comments and answers for clarification:
- The method
__check_for_valid_token
name can be changed to not run into name mangling issues. I was just using double underscore because it was a method supposedly only accessible by the class itself (private). - There is no inheritance in "MyClass".
- The
@LOGIN_REQUIRED
code must run before the@ADMIN_REQUIRED
code (as that is what someone expects, at least in my case).