Flask - 两个参数化函数出错

时间:2017-10-13 16:25:15

标签: python flask

我使用this方法构建了一个函数包装器:

def parametrized(dec):

    def layer(*args, **kwargs):
        def repl(f):
            return dec(f, *args, **kwargs)

        return repl

    return layer


@parametrized
def role_required(f, roles):
    print(roles)

    def decorated_function(*args, **kwargs):
        print('in dec func') # never called
        auth_mod_used = 'auth' in app.blueprints.keys()
        if auth_mod_used:
            print(g.user.role.lower())
            print(g.user.role.lower() in (role.lower for role in roles))
            if g.user is None or g.user.role.lower() not in (role.lower for role in roles):
                flash('You are not authorized to preform this action.', 'danger')
                # TODO: log to logging service
                return redirect(url_for('home.index'))
            return f(*args, **kwargs)
        return f(*args, **kwargs)

    return decorated_function

它的目的是通过仅允许特定角色通过来保护路线。我试图这样使用它:

@mod_lp.route('/add', methods=['POST'])
@role_required(['admin', 'principal'])
def add():
    form = LessonPlanForm()
    if form.validate_on_submit():
        lp = LessonPlan(form.name.data, form.class_day.data)
        db.session.add(lp)
        db.session.commit()
    return redirect(url_for('lesson_plan.index'))

错误:

  

无法为端点' lesson_plan.add'

构建网址

1 个答案:

答案 0 :(得分:1)

发现此问题。参数化函数从未调用传递给它的函数。我需要这一行:

@wraps(f)

在函数中,如下:

@parametrized
def role_required(f, roles):
    @wraps(f)
    def decorated_function(*args, **kwargs):
    # and so on