装饰器在 Flask 中不起作用。

huangapple go评论104阅读模式
英文:

Decorator doesn't works in flask

问题

我正在为Flask编写一个装饰器,用于检查用户是否已经验证:

  1. def not_login_required(func):
  2. def wrapper(*args, **kwargs):
  3. if current_user.is_authenticated:
  4. return redirect('/')
  5. return func(*args, **kwargs)
  6. return wrapper

但是当我使用它时:

  1. @not_login_required
  2. @app.route('/login/', methods=['GET', 'POST'])
  3. def login():
  4. # 许多代码

它什么也不做。

英文:

I was writing a decorator for flask which checks if user is authenticated:

  1. def not_login_required(func):
  2. def wrapper(*args, **kwargs):
  3. if current_user.is_authenticated:
  4. return redirect('/')
  5. return func(*args, **kwargs)
  6. return wrapper

But when I use it

  1. @not_login_required
  2. @app.route('/login/', methods=['GET', 'POST'])
  3. def login():
  4. # many code

It does nothing

答案1

得分: 1

The route() decorator必须是最外层的装饰器,根据文档的说明:

要使用这个装饰器,将它应用为视图函数的最内层装饰器。在应用其他装饰器时,始终要记住route()装饰器是最外层的。

因此,您的代码应该如下所示:

  1. @app.route('/login/', methods=['GET', 'POST'])
  2. @not_login_required
  3. def login():
  4. # 多行代码
英文:

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:

  1. @app.route('/login/', methods=['GET', 'POST'])
  2. @not_login_required
  3. def login():
  4. # many code

答案2

得分: 0

我编辑了装饰器如下:

  1. from functools import wraps
  2. # ...
  3. def not_login_required(name):
  4. def decorator(func):
  5. @wraps(func)
  6. def wrapped(*args, **kwargs):
  7. if current_user.is_authenticated:
  8. return redirect('/')
  9. return func(*args, **kwargs)
  10. return wrapped
  11. return decorator

并且我改变了顺序:

  1. @app.route('/login/', methods=['GET', 'POST'])
  2. @not_login_required('login')
  3. def login():
  4. # 许多代码
英文:

I edited decorator like there

  1. from functools import wraps
  2. # ...
  3. def not_login_required(name):
  4. def decorator(func):
  5. @wraps(func)
  6. def wrapped(*args, **kwargs):
  7. if current_user.is_authenticated:
  8. return redirect('/')
  9. return func(*args, **kwargs)
  10. return wrapped
  11. return decorator

And I changed order:

  1. @app.route('/login/', methods=['GET', 'POST'])
  2. @not_login_required('login')
  3. def login():
  4. # many code

huangapple
  • 本文由 发表于 2023年6月16日 00:20:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定