Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use an argument returned by a decorator in another decorator that is called after the first decorator

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 31
    Answer it

    I am using two decorators to decorate a function "add_user", the first one @auth_user authenticates the logged in user via json web token request headers and returns the user's information as an argument "user_info" back to the decorated function add_user. The second decorator @has_permission is supposed to check whether or not the user has permissions on the requested resource. I wanted to pass the user's information returned as user_info by @auth_user to @has_permission but don't know how to do that, here is the code so far:

     

    @has_permission
    @auth_user
    def add_user(user_info):
        """
        do something
        """
        return None

     

    The decorators:

     

    def auth_user(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            data = jwt.decode(request.headers['some-access-token'], some_secret_key)
            try:
                user_info = User.query.filter(User.id==data['user_id']).first()
            except:
                return jsonify({"message" : "error"}), 401
    
            return f(user_info, *args, **kwargs)
    
        return wrapper

     

    and the second decorator where I want to access the user_info:

     

    def has_permission(f):
        wraps(f)
        def wrapper(*args, **kwargs):
            # This is where I want to access the user information instead of processing the key again #
            # return some new_args ... #
            return f(*args, **kwargs)
        return wrapper

     

    What is the best way to achieve this? 

 0 Answer(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: