What's the point of the “is_authenticated” method used in Flask-Login?

十年热恋 提交于 2020-01-29 02:51:30

问题


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, and is_anonymous seem quite strange to me - when would they ever return anything other than their predefined value?

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


回答1:


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.

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.




回答2:


I was baffled by this is_authenticated vs is_anonymous for hours. I could not believe they were just opposite. Finally just by chance I found this old blog post. It is about a problem in the Django templating system in which non existent variables evaluates to False. That could lead to wrong behaviour when testing is_anonymous in the template code. Again that is old so I don't know if it holds. The way they solved the problem was to create is_authenticated.

I guess Flask-Login just copied the model from Django without questioning. Now I can sleep in peace.



来源:https://stackoverflow.com/questions/19532372/whats-the-point-of-the-is-authenticated-method-used-in-flask-login

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!