How Can I Detect Whether a Variable Exists in Flask Session?

I would like to detect if a session['logged_in'] key exists, which means my user has already logged in.

For Example:

if (session['logged_in'] != None):
    if session['logged_in'] == True:
        return redirect(url_for('hello'))

However, if the key 'logged_in' doesnt exist it therefore generates an error. As a session object is like a dictionary I thought I would be able to use the had_key() method, but this doesn't seem to work either. Is there an easy way to detect if a session contains data without generating an error?

1

5 Answers

In general, accessing session items is as simple as using a dictionary.

You could use has_key() (there is no had_key() method), but it would be better to use in or get(). An example flask app that accesses session items:

from flask import Flask, session, request, redirect, url_for

app = Flask(__name__)

@app.route('/')
def index():
    if session.get('logged_in') == True:
        return 'You are logged in'
    return 'You are not logged in'

@app.route('/login')
def login():
    session['logged_in'] = True
    return redirect(url_for('index'))

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.secret_key = 'ssssshhhhh'
    app.run()

You can use something like this to check if a key exists in the session dict:

if session.get('logged_in'):
    if session['logged_in']:
        return redirect(url_for('hello'))
if session.get('logged_in') is not None:
    # do something for logged in user
    return render_template('success.html')
else:
    # do something for non-logged in user
    return render_template('index.html')

Give that a try, it should work.

Sorry for the belated answer, but was struggling upon the same things myself and this is the basic formula.

In my scenario, I have a users table in a mysql database, by which when a user logs in or creates an account, a session variable is created and set to that user's id.

If this user now navigates to root ('/'), the session variable is detected and the success.html is served.

If no value for session['logged_in'] is found, than index.html is served, where they can create an account or login.

As @rnevius mentioned, if the underlying issue you are trying to solve is testing to see if the current user is logged in then you might be better off using some built-in Flask functionality.

If you are just trying to find out if a certain key (logged_in) exists within the session object, you can treat the session object as if it was a dictionary and simply use the following syntax:

if session.get('logged_in') is not None:
  # Here we know that a logged_in key is present in the session object.
  # Now we can safely check it's value
  if session['logged_in'] == True:
      return redirect(url_for('hello'))
2
# Check if key exists
if session.get("key") == None:
    # Do something if it doesnt exist
else:
    # Do something else if it does exist

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest