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'
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)
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With