装饰器在 Flask 中不起作用。

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

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

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:

确定