How to track the current user in flask-login? How to track the current user in flask-login? flask flask

How to track the current user in flask-login?


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 classfrom flask.ext.login import AnonymousUserMixinclass 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.


Well, the error message says it all. There is no logged in user, so current_user returns an AnonymousUserMixin. AnonymousUserMixin implements the interface described here: http://flask-login.readthedocs.org/en/latest/#your-user-class (which does not include a username property). Try something like this:

@pot.before_requestdef load_users():    if current_user.is_authenticated():        g.user = current_user.get_id() # return username in get_id()    else:        g.user = None # or 'some fake value', whatever

Obviously, the rest of your code has to deal with the possibility that g.user will not refer to a real user.


AnonymousUserMixin has no username attribute. You need to overwrite the object and call the mixin. Have a look at LoginManager.anonymous_user which is an object which is used when no user is logged in.

You also need to get the user from somewhere. There is no point in storing the username in g as you could just use current_user.username.

If you wanted to get the username you would need too

if current_user.is_authenticated():    g.user = current_user.username

This would require that the user object has a property called username. There are lots of ways to customize Flask-Logins use

I suggest re-reading the docs and taking a look at the source code:

https://github.com/maxcountryman/flask-login/blob/master/flask_login.py

Joe