“is_authenticated"有什么意义?Flask-Login 中使用的方法? [英] What's the point of the "is_authenticated" method used in Flask-Login?

查看:61
本文介绍了“is_authenticated"有什么意义?Flask-Login 中使用的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在学习 Flask Mega-Tutorial,我遇到了这段代码:

I'm working through the Flask Mega-Tutorial right now and I've come across this bit of code:

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 对我来说似乎很奇怪——他们什么时候会返回预定义值以外的任何东西?

is_authenticated, is_active, and is_anonymous seem quite strange to me - when would they ever return anything other than their predefined value?

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

Could somebody explain to me why Flask-Login makes me use these seemingly useless methods?

推荐答案

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

First of all, is_anonymous() and is_authenticated() are each other's inverse. You could define one as the negation of the other, if you want.

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

You can use these two methods to determine if a user is logged in.

当没有人登录 Flask-Login 时,current_user 被设置为 AnonymousUser 对象.这个对象用 False 响应 is_authenticated()is_active() ,用 响应 is_anonymous()真的.

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.

is_active() 方法还有一个重要的用途.不是像我在教程中建议的那样总是返回 True,您可以让它为禁止或停用的用户返回 False,并且这些用户将不被允许登录.

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.

这篇关于“is_authenticated"有什么意义?Flask-Login 中使用的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆