Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve session data with Flask?

I have flask+wtforms application. I can see in login() user object stored as

  if user:
   if user.verify_password(form.password.data):
    flash('You have been logged in')
    user.logins += 1

    db.session.add(History(user.uid))
    db.session.commit()

    session['user'] = user

Now I wanted to retrieve the user

if 'user' in session:
       User=session.get('user')
       print User.nickname ###<< how to retrieve specific object member?

It fails with message like :

Instance <User at 0x8e5a64c> is not bound to a Session; attribute refresh operation cannot proceed
like image 877
webminal.org Avatar asked Mar 23 '13 20:03

webminal.org


People also ask

How do I get data from a Flask session?

It's simple. If you want to retrieve a specific object simply add the name of the variable within session, e.g. session['nickname'] . You can set the variable the same way, by doing session['nickname'] = nickname . This is an simplified version of the function I use for login.

How does session work in Flask?

Flask-Session is an extension for Flask that supports Server-side Session to your application. The Session is the time between the client logs in to the server and logs out of the server. The data that is required to be saved in the Session is stored in a temporary directory on the server.


1 Answers

It's simple. If you want to retrieve a specific object simply add the name of the variable within session, e.g. session['nickname'].

You can set the variable the same way, by doing session['nickname'] = nickname.

In your case you would change it to the following

if 'user' in session:
    user = session['user']
    print user

if 'nickname' in session:
    nickname = session['nickname']
    print nickname

This is an simplified version of the function I use for login.

@app.route('/login', methods=['POST'])
def login():
    """Authenticate User"""
    username = request.form['username'].strip()
    nickname = request.form['nickname'].strip()
    password = request.form['password']
    try:
        if Auth().VerifyLogin(username, password):
            session['username'] = username
            session['nickname'] = nickname
        else:
            # failed to login, do something.
    except Exception as why:
        app.logger.critical('.....')
like image 86
eandersson Avatar answered Sep 27 '22 16:09

eandersson