Search code examples
pythonflaskflask-login

How do you track the current user in flask-login?


I'm trying to use the current user in my view from flask-login. So I tried to use the g object

I'm assigning flask.ext.login.current_user to the g object

@pot.before_request
def load_users():
    g.user = current_user.username

It works if the user is correct. But when I sign-up or login with the wrong credentials I get this error:

`AttributeError: 'AnonymousUserMixin' object has no attribute 'username'`

Please enlight me where am I wrong...


Solution

  • Thanks for your answer @Joe and @pjnola, as you all suggested i referred flask-login docs

    I found that we can customize the anonymous user class, so i customized for my requirement,

    Anonymous class

    #!/usr/bin/python
    #flask-login anonymous user class
    from flask.ext.login import AnonymousUserMixin
    class Anonymous(AnonymousUserMixin):
      def __init__(self):
        self.username = 'Guest'
    

    Then added this class to anonymous_user

    login_manager.anonymous_user = Anonymous

    From this it was able to fetch the username if it was anonymous request.