How to retrieve session data with Flask?

45,253

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('.....')
Share:
45,253
webminal.org
Author by

webminal.org

Free and Open Source programmer. Projects include: FileSystem Projects and Free Online Linux Terminal

Updated on February 18, 2022

Comments

  • webminal.org
    webminal.org about 2 years

    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
    
  • webminal.org
    webminal.org about 11 years
    How to retrieve ,if its an object? Please check above edit code part. 'user' is an object which has members like user.uid,user.logins and user.nickname
  • webminal.org
    webminal.org about 11 years
    Thanks a lot,got it. Used your first method. Not worrying about objects and things like that. Stored the nickname as session variable rather than object. Thanks for the help.
  • eandersson
    eandersson about 11 years
    No worries. btw for security reasons it's best to store the least amount of information in the session possible. I store all my permissions etc in a database.
  • webminal.org
    webminal.org about 11 years
    the app uses mysql, I don't have much data stored session. Just now trying to re-use session..in order to add a new user-edit profile page in the website.
  • TimStaley
    TimStaley almost 11 years
    Note also that session cookies have a size limit of 4kb - over that and the session gets blanked, which can cause some confusing bugs!