Search code examples
flask

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?


Solution

  • You can use in keyword for keys method:

    # Check if key exists
    if 'logged_in' in session.keys():
        if session['logged_in'] == True:
            return redirect(url_for('hello'))