Home > other >  Flask problem: decorators are overwriting each other
Flask problem: decorators are overwriting each other

Time:10-14

I am working on creating a flask application with users that must log in. So I made two decorators, login_required and admin_required to check if the user is logged in and if they are an admin. This is the code:

# decorator so that users must be logged in to access the page.
def login_required(view):
    wraps(view)

    def log_req(**kwargs):
        if session['a_id'] is None:
            return redirect(url_for('website.login'))

        return view(**kwargs)

    return log_req


# decorator so that users must be an admin to access the page.
def admin_required(view):
    wraps(view)

    def adm_req(**kwargs):
        if session['role'] != 'admin':
            return redirect(url_for('wesite.portal_home'))

        return view(**kwargs)

    return adm_req

This is the route:

@website.route('/api/register-user', methods=('POST',))
@login_required
@admin_required
def register_user():
    ...

However, it gives me this error:

AssertionError: View function mapping is overwriting an existing endpoint function: website.log_req

If I reverse the order of the decorators, then it says that website.adm_req is being overwritten.

Why is that happening, and how can I fix this problem?

CodePudding user response:

I found the problem. wraps(view) should be the decorator @wraps(view). This is the fixed function:

# decorator so that users must be logged in to access the page.
def login_required(view):
    @wraps(view)
    def log_req(**kwargs):
        if session['a_id'] is None:
            return redirect(url_for('website.login'))

        return view(**kwargs)

    return log_req
  • Related