Flask decorator:无法从URL传递参数 [英] Flask decorator : Can't pass a parameter from URL
问题描述
我对瓶子很新,我正在尝试使用装饰者的潜力:p
我读了很多东西,发现了大量关于python装饰器的主题,但没有什么实际的帮助。 >
i'm quite new with flask and i'm trying to use the migthy power of decorators :p I read lot of things and found tons of topics about python decorators here but nothing really helpful.
@app.route('groups/<id_group>')
@group_required(id_group)
@login_required
def groups_groupIndex(id_group):
#do some stuff
return render_template('index_group.html')
这是我得到的错误:
This is the error i get :
@group_required(id_group), NameError: name 'id_group' is not defined
好的,id_group尚未定义,但我不明白为什么我可以在函数groups_groupIndex中使用id_group参数,但不能在装饰器中使用!
Ok, id_group is not defined yet, but I don't understand why i CAN use the id_group parameter from the URL in the function groups_groupIndex but NOT in the decorator!
我尝试移动/切换装饰器,但每次都发生相同的错误。
I try to move/switch decorators, but the same error occure each time.
这是我的装饰器,但它似乎工作正常
Here is my decorator, but it seems to work fine
def group_required(group_id):
def decorated(func):
@wraps(func)
def inner (*args, **kwargs):
#Core_usergroup : table to match users and groups
groups = Core_usergroup.query.filter_by(user_id = g.user.id).all()
for group in groups:
#if the current user is in the group : return func
if int(group.group_id) == int(group_id) :
return func(*args, **kwargs)
flash(gettext('You have no right on this group'))
return render_template('access_denied.html')
return inner
return decorated
也许我没有看到像我应该装饰者...我可以使用我的装饰这种方式或需要我重写不同的东西?
Maybe i don't see decorators like i should... Can i use my decorator this way or need i rewrite something different ?
推荐答案
您将 group_id
定义为函数参数;这使得它成为该函数中的本地名称。
You defined group_id
as a function parameter; that makes it a local name in that function.
这不会使名称可用于其他作用域;装饰器所在的全局名称空间看不到该名称。
That doesn't make the name available to other scopes; the global namespace that the decorator lives in cannot see that name.
然而, wrapper 函数可以。在调用时,它将从 @ apps.route()
包装器中传递该参数:
The wrapper function, however, can. It'll be passed that parameter from the @apps.route()
wrapper when called:
def group_required():
@wraps(func)
def wrapper(group_id, *args, **kwargs):
#Core_usergroup : table to match users and groups
groups = Core_usergroup.query.filter_by(user_id = g.user.id).all()
for group in groups:
#if the current user is in the group : return func
if int(group.group_id) == int(group_id) :
return func(*args, **kwargs)
flash(gettext('You have no right on this group'))
return render_template('access_denied.html')
return wrapper
这篇关于Flask decorator:无法从URL传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!