Flask-Login中使用的"is_authenticated"方法有什么意义?

use*_*531 14 python flask web flask-login flask-extensions

我正在研究Flask Mega-Tutorial,我遇到了这段代码:

class User(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    nickname = db.Column(db.String(64), unique = True)
    email = db.Column(db.String(120), unique = True)
    role = db.Column(db.SmallInteger, default = ROLE_USER)
    posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.id)

    def __repr__(self):
        return '<User %r>' % (self.nickname)
Run Code Online (Sandbox Code Playgroud)

is_authenticated,is_active和is_anonymous对我来说似乎很奇怪 - 他们何时会返回除预定义值以外的任何内容?

有人可以向我解释为什么Flask-Login让我使用这些看似无用的方法吗?

Mig*_*uel 33

首先,is_anonymous()is_authenticated()互为倒数.如果你愿意,你可以将一个定义为另一个的否定.

您可以使用这两种方法来确定用户是否已登录.

When nobody is logged in Flask-Login's current_user is set to an AnonymousUser object. This object responds to is_authenticated() and is_active() with False and to is_anonymous() with True.

The is_active() method has another important use. Instead of always returning True like I proposed in the tutorial, you can make it return False for banned or deactivated users and those users will not be allowed to login.


Clo*_*eto 9

几个小时以来,我is_authenticated对这个vs 感到困惑is_anonymous.我简直不敢相信他们正好相反.最后我偶然发现了这篇老博文.它是关于Django模板系统中存在的一个问题,其中不存在的变量的计算结果为False.is_anonymous在模板代码中进行测试时,这可能会导致错误的行为.这又是旧的,所以我不知道它是否成立.他们解决问题的方法是创造is_authenticated.

我猜Flask-Login只是从Django复制模型而没有质疑.现在我可以安然入睡.