Flask decorator : Can't pass a parameter from URL

大兔子大兔子 提交于 2019-12-05 16:52:17

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.

The wrapper function, however, can. It'll be passed that parameter from the @apps.route() wrapper when called:

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

Note that this decorator doesn’t bother with passing on the group_id parameter to the decorated function; use return func(group_id, *args, **kwargs) instead of you still need access to that value in the view function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!