Ayad Salim
Ayad Salim

Reputation: 98

Multi-Level decorator in Flask

I'm developing Flask application and I have a decorator called login_required which checks if the user is logged in, and sends the current user to the next function.

def login_required(function):
    @wraps(function)
    def decorator(*args, **kwargs):
        token = None
        if 'x-access-tokens' in request.headers:
            token = request.headers['x-access-tokens']

        if not token:
            return jsonify({'message': 'a valid token is missing'}), 401
        try:
            data = jwt.decode(token, app.secret_key)
            current_user = User.query.filter_by(username=data['username']).first()
        except:
            return jsonify({'message': 'token is invalid'}), 401

        return function(current_user, *args, **kwargs)

    return decorator

So, the callback function is declared like this.

@blueprint.route('/settings', methods=['GET'])
@login_required
def settings(current_user):
    # here I check if the current_user is admin or not
    ...
    # function body

Now I want to implement an admin_required decorator which depends on login_required decorator, to be easy using it within functions like this.

@blueprint.route('/settings', methods=['GET'])
@admin_required
def settings(current_user):
    ...
    # function body

How can I achieve this?

Upvotes: 0

Views: 47

Answers (1)

Deepak Tripathi
Deepak Tripathi

Reputation: 3233

So you can create your functionality like this

def decorator1(function):
  def fun(*args, **kwargs):
    user = function(*args, **kwargs)
    print("here")
    return user
  return fun



def decorator2(function):
  def fun(*args, **kwargs):
    # firslty i will decorate function with decorator1
    decor1 = decorator1(function)
    decor1_result = decor1(*args, **kwargs)
    # do operation with above result in your case now check if user is admin
    print("here in decor2")
    return decor1_result + 5
  return fun


@decorator2
def test_function(a,b):
  return a+b

# Now you want to access a+b and then add c to it

I have included comments for better understanding. In your case decorator1 will be login_required decorator and decorator2 will be admin_check decorator. So while creating admin check decorator you can access login_required decorator inside it.

Upvotes: 1

Related Questions