Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect whether a variable exists in Flask session?

Tags:

flask

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?

like image 399
Brad Nielsen Avatar asked Mar 08 '15 10:03

Brad Nielsen


People also ask

How do I check if a session variable exists?

You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable.

How do you store variables in a Flask session?

In the flask, a session object is used to track the session data which is a dictionary object that contains a key-value pair of the session variables and their associated values. The following syntax is used to set the session variable to a specific value on the server.

How do I get data from a session in Flask?

To release a session variable use pop() method. The following code is a simple demonstration of session works in Flask. URL '/' simply prompts user to log in, as session variable 'username' is not set. As user browses to '/login' the login() view function, because it is called through GET method, opens up a login form.


3 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()
like image 168
mhawke Avatar answered Oct 21 '22 10:10

mhawke


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'))
like image 10
Matt Healy Avatar answered Oct 21 '22 10:10

Matt Healy


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.

like image 6
twknab Avatar answered Oct 21 '22 12:10

twknab