Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track the current user in flask-login?

Tags:

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

like image 556
naga4ce Avatar asked Oct 09 '13 13:10

naga4ce


People also ask

How do I see current users in a Flask?

In your login function just store the value like: first import the session from flask. Then use like this. then use it like {{ session['username'] }} in your template. Is this recommended for flask security because it takes care of all of the user login management.

Does Flask-login use session?

By default, Flask-Login uses sessions for authentication. This means you must set the secret key on your application, otherwise Flask will give you an error message telling you to do so. See the Flask documentation on sessions to see how to set a secret key.


1 Answers

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.

like image 154
naga4ce Avatar answered Oct 05 '22 12:10

naga4ce