Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask.session persisting after close browser

Tags:

session

flask

I want to be able to detect if a user has closed a browser since last logging into a Flask site. I have read that Flask sessions are supposed to expire on closing the browser, but the session data is stored on the server as far as I can tell and is persisting across browser sessions. How can I clear all session data when the user closes the browser?

mainapp.py:

@mainapp.route('/')
def home():
    if 'user_name' in session:
        logger.debug( 'Logged in as {0}'.format(escape(session['user_name'])))
    return render_template('home.html')

userviews.py:

@userviews.route("/login", methods=["GET", "POST"])
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():
        #get user from db
        session['user_name'] = user.user_name

setup.py:

app.secret_key = 'somethingreallysecret'
like image 570
Don Smythe Avatar asked May 14 '16 14:05

Don Smythe


2 Answers

Because the flask session uses cookies, the data is persisted even if the user closes the window. You can track use closing the window with Flask-SocketIO.

If you want to remove a specific key from session:

from flask import session
from flask_socketio import SocketIO, emit
from flask.ext.login import current_user, logout_user

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@socketio.on('disconnect')
def disconnect_user():
    logout_user()
    session.pop('yourkey', None)
like image 128
Amin Alaee Avatar answered Oct 19 '22 13:10

Amin Alaee


It seems that contrary to vanilla Flask, the sessions opened in Flask-session are permanent by default, from the documentation:

By default, all non-null sessions in Flask-Session are permanent.

So maybe try to set SESSION_PERMANENT=False?

like image 2
user9142797 Avatar answered Oct 19 '22 14:10

user9142797