【问题标题】:Defining decorator for a view function in flask在烧瓶中为视图函数定义装饰器
【发布时间】:2014-08-25 05:13:28
【问题描述】:

我试图在flask中实现一个最小的登录系统,所以我定义了一个装饰器来检查会话中的一个元素是否具有特定的值,如果是,用户就无法访问由该装饰器包装的页面.

这是包装好的视图函数:

@mustBelongToARoom
@app.route('/draw')
def draw():
    return render_template('draw.html')

这是装饰器

def mustBelongToARoom(f):
    @wraps(f)
    def wrap_f(*args, **kwargs):
        print 'test\n'
        if session['room_name'] is None:
            return render_template(url_for('/'))
        return f(*args, **kwargs)
    return wrap_f

因此,基本上,如果room_nameNone,则用户无法访问draw 页面。 问题是它似乎忽略了装饰器添加的代码。例如,以这个版本的mustBelongToARoom 装饰器为例:

   def mustBelongToARoom(f):
        @wraps
        def wrap_f(*args, **kwargs):
            print 'test\n'
            if session['room_name'] is None:
                print '[DEBUG] you are not allowed to acces this page!\n'
                return render_template(url_for('/'))
            return f(*args, **kwargs)
        return wrap_f

当用户尝试访问draw 页面时,我希望在控制台中看到[DEBUG] you are not allowed to acces this page!\n,但它没有显示。

【问题讨论】:

    标签: python debugging flask python-decorators


    【解决方案1】:

    尝试颠倒您应用装饰器的顺序。路由装饰器只添加了draw() 函数,而不是mustBelongToARoom 返回的函数,其中包含您的身份验证方案。

    装饰器如何工作的一个很好的参考:How to make a chain of function decorators?

    【讨论】:

      猜你喜欢
      • 2021-04-06
      • 2012-07-14
      • 1970-01-01
      • 2018-02-17
      • 2019-11-13
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 2013-08-21
      相关资源
      最近更新 更多