小编Tho*_* N.的帖子

Flask decorator:无法从URL传递参数

我是一个很新的烧瓶,我正在尝试使用装饰器的迁移能力: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')
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

@group_required(id_group), NameError: name 'id_group' is not defined
Run Code Online (Sandbox Code Playgroud)

好的,id_group尚未定义,但我不明白为什么我可以使用函数groups_groupIndex中的URL中的id_group参数,但不能在装饰器中使用!

我尝试移动/切换装饰器,但每次都会出现同样的错误.

这是我的装饰,但似乎工作正常

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 …
Run Code Online (Sandbox Code Playgroud)

python decorator flask python-decorators

4
推荐指数
1
解决办法
2733
查看次数

标签 统计

decorator ×1

flask ×1

python ×1

python-decorators ×1