Python 烧瓶装饰器:罐';无法从URL传递参数

Python 烧瓶装饰器:罐';无法从URL传递参数,python,flask,decorator,python-decorators,Python,Flask,Decorator,Python Decorators,我对烧瓶很陌生,我正试图利用装饰师的强大力量:p 我在这里读了很多东西,发现了很多关于python装饰器的主题,但没有什么真正有用的 @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') 好的,

我对烧瓶很陌生,我正试图利用装饰师的强大力量:p 我在这里读了很多东西,发现了很多关于python装饰器的主题,但没有什么真正有用的

@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')
好的,id\u group还没有定义,但是我不明白为什么我可以在function groups\u groupIndex中使用URL中的id\u group参数,而不能在decorator中使用

我尝试移动/切换装饰器,但每次都会发生相同的错误

这是我的装潢师,但看起来不错

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

也许我没有看到我应该看到的装饰师。。。我可以这样使用我的decorator吗?或者我需要重写一些不同的东西吗?

您将
组id
定义为函数参数;这使它成为该函数中的本地名称

这不会使名称对其他作用域可用;装饰程序所在的全局命名空间无法看到该名称

但是,包装器函数可以。调用时,将从
@apps.route()
包装中传递该参数:

def group_required(func):
    @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

请注意,此装饰器不需要将
group\u id
参数传递给装饰函数;使用
return func(group_id,*args,**kwargs)
而不是您仍然需要在view函数中访问该值

我知道这是范围问题,非常感谢,它现在工作得很好:)@anjalis,这仍然会作为显式参数传入
group\u id
。调用时,Python从
**…
映射中解压参数。如果测试失败,那是因为包装器没有将
group\u id
传递给view函数。@sudocoder:很抱歉,虽然
func
确实丢失了,但这里的装饰程序明确要求装饰函数至少接受一个位置参数
group\u id
。你链接的另一篇文章可能会删除这个要求,但这并不是让这个装饰器工作的严格要求。如果它对你不起作用,那就是出了问题。
def group_required(func):
    @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