gpt4 book ai didi

python - Flask - 两个参数化函数出错

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:27 34 4
gpt4 key购买 nike

我使用 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'))

错误:

Could not build url for endpoint 'lesson_plan.add'

最佳答案

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

@wraps(f)

在函数中,像这样:

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

关于python - Flask - 两个参数化函数出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46734219/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com