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.
| 归档时间: |
|
| 查看次数: |
6162 次 |
| 最近记录: |