【问题标题】:Flask - Error with two parameterized functionsFlask - 两个参数化函数出错
【发布时间】:2018-03-25 20:15:25
【问题描述】:

我使用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”构建 url

【问题讨论】:

    标签: python flask


    【解决方案1】:

    发现了这个问题。参数化函数从未调用传递给它的函数。我需要这条线:

    @wraps(f)
    

    在函数中,像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 2015-01-28
      • 2017-11-30
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      相关资源
      最近更新 更多