Why isn't my current_user authenticated in flask-login?

元气小坏坏 提交于 2019-12-05 08:29:09
dirn

You have a method named User.is_authenticated. Inside User.__init__, though, you set an attribute with the same name.

self.is_authenticated = False

This overrides the method. Then, whenever you check current_user.is_authenticated, you are accessing the attribute that's always false.

You should remove the assignment from __init__ and change is_authenticated to the following:

def is_authenticated(self):
    return True

If you need it to be dynamic for some reason, rename the attribute so it doesn't shadow the method.

def is_authenticated(self):
    return self._authenticated

Another problem is with your load_user function.

Instead of filtering for User.id==user_id, you are getting it. The user wasn't being returned because load_user is returning User.query.get(True) instead of User.query.get(user_id).

If you make the following change, it will work:

@login_manager.user_loader
def load_user(user_id):
    try:
        return User.query.get(user_id)
    except:
        return None
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!