How to track the current user in flask-login?

2020-02-25 03:54发布

问题:

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

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

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

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

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

Please enlight me where am i wrong...

回答1:

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.



回答2:

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_request
def 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.



回答3:

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