我正在学习 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)
is_authenticated、is_active 和 is_anonymous 对我来说似乎很奇怪 - 他们什么时候会返回除预定义值之外的任何内容?
有人可以向我解释为什么 Flask-Login 让我使用这些看似无用的方法吗?
最佳答案
首先,is_anonymous()
和is_authenticated()
互为逆。如果需要,您可以将一个定义为另一个的否定。
您可以使用这两种方法来确定用户是否已登录。
当没有人登录时,Flask-Login 的 current_user
被设置为一个 AnonymousUser
对象。此对象以 False
响应 is_authenticated()
和 is_active()
并以 响应
。is_anonymous()
是的
is_active()
方法还有另一个重要的用途。不要像我在教程中建议的那样总是返回 True
,您可以让它为被禁止或停用的用户返回 False
,并且不允许这些用户登录。
关于python - Flask-Login 中使用的 "is_authenticated"方法有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19532372/