[英]Defining decorator for a view function in flask
I've tried to implement a minimal login sysem in flask, so I defined a decorator that checks if an element from the session has a particular value, if it does, the user can't access the page wrapped by that decorator. 我试图在flask中实现最小登录系统,所以我定义了一个装饰器,该装饰器检查会话中的元素是否具有特定值,如果存在,则用户无法访问该装饰器包装的页面。
This is the wrapped view function: 这是包装视图功能:
@mustBelongToARoom
@app.route('/draw')
def draw():
return render_template('draw.html')
And this is the decorator 这是装饰
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
So, basically, if the room_name
is None
the user can't access the draw
page. 因此,基本上,如果room_name
为None
则用户将无法访问draw
页面。 The problem is that it seems to ignore the code added by the decorator. 问题在于它似乎忽略了装饰器添加的代码。 For example, take this version of the mustBelongToARoom
decorator: 例如,使用以下版本的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
I'd expect to see [DEBUG] you are not allowed to acces this page!\\n
in the console when an user tries to acces the draw
page, but it doesn't display it. 我希望看到[DEBUG] you are not allowed to acces this page!\\n
在控制台中,当用户尝试访问draw
页面时,它不会显示。
Try reversing the order you apply the decorator. 尝试颠倒您应用装饰器的顺序。 The route decorator only added the draw()
function and not the one returned by mustBelongToARoom
, which includes your authentication scheme. 路由装饰器仅添加了draw()
函数,而未添加mustBelongToARoom
返回的mustBelongToARoom
(其中包括您的身份验证方案)。
A good reference for how decorators work: How to make a chain of function decorators? 装饰器如何工作的一个很好的参考: 如何制作功能装饰器链?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.