英文:
Decorator doesn't works in flask
问题
我正在为Flask编写一个装饰器,用于检查用户是否已经验证:
def not_login_required(func):
def wrapper(*args, **kwargs):
if current_user.is_authenticated:
return redirect('/')
return func(*args, **kwargs)
return wrapper
但是当我使用它时:
@not_login_required
@app.route('/login/', methods=['GET', 'POST'])
def login():
# 许多代码
它什么也不做。
英文:
I was writing a decorator for flask which checks if user is authenticated:
def not_login_required(func):
def wrapper(*args, **kwargs):
if current_user.is_authenticated:
return redirect('/')
return func(*args, **kwargs)
return wrapper
But when I use it
@not_login_required
@app.route('/login/', methods=['GET', 'POST'])
def login():
# many code
It does nothing
答案1
得分: 1
The route()
decorator必须是最外层的装饰器,根据文档的说明:
要使用这个装饰器,将它应用为视图函数的最内层装饰器。在应用其他装饰器时,始终要记住
route()
装饰器是最外层的。
因此,您的代码应该如下所示:
@app.route('/login/', methods=['GET', 'POST'])
@not_login_required
def login():
# 多行代码
英文:
The route()
decorator must be the outermost decorator, according to the docs:
> To use the decorator, apply it as innermost decorator to a view function. When applying further decorators, always remember that the route()
decorator is the outermost.
So your code should look like this:
@app.route('/login/', methods=['GET', 'POST'])
@not_login_required
def login():
# many code
答案2
得分: 0
我编辑了装饰器如下:
from functools import wraps
# ...
def not_login_required(name):
def decorator(func):
@wraps(func)
def wrapped(*args, **kwargs):
if current_user.is_authenticated:
return redirect('/')
return func(*args, **kwargs)
return wrapped
return decorator
并且我改变了顺序:
@app.route('/login/', methods=['GET', 'POST'])
@not_login_required('login')
def login():
# 许多代码
英文:
I edited decorator like there
from functools import wraps
# ...
def not_login_required(name):
def decorator(func):
@wraps(func)
def wrapped(*args, **kwargs):
if current_user.is_authenticated:
return redirect('/')
return func(*args, **kwargs)
return wrapped
return decorator
And I changed order:
@app.route('/login/', methods=['GET', 'POST'])
@not_login_required('login')
def login():
# many code
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论