0

I'm learning flask and am trying to associate some randomly generated data with each session. I use the approach from this answer to set session.permanent to False, but closing the browser, then reopening it at going back to the page still displays the same code.

MWE:

from flask import Flask, session
import numpy as np

app = Flask(__name__)
app.secret_key = "supersecretkey"

@app.before_request
def make_session_permanent():
    session.permanent = False

@app.route('/')
def index():
    if 'id' not in session:
        random_id = "".join(np.random.choice(list("abcdefg123"), 16))
        session["id"] = random_id
    return session['id']

if __name__ == '__main__':
    app.run(debug=True)

Update: Based on this answer someone recommended to use socketio to notice disconnects. This also makes no difference, i.e. closing the browser, reopening it, and going to 127.0.0.1:5000 gives the same number as before closing. An updated MWE using this is below:

from flask import Flask, session
from flask_socketio import SocketIO
import numpy as np

app = Flask(__name__)
app.secret_key = "supersecretkey"

@app.before_request
def make_session_permanent():
    session.permanent = False

@app.route('/')
def index():
    if 'id' not in session:
        random_id = "".join(np.random.choice(list("abcdefg123"), 16))
        session["id"] = random_id
    return session['id']

socketio = SocketIO(app)
@socketio.on('disconnect')
def disconnect_user():
    session.pop('id', None)


if __name__ == '__main__':
    app.run(debug=True)
bjarkemoensted
  • 2,557
  • 3
  • 24
  • 37

1 Answers1

1
# Instantiate a new web application called `app`, 
# with `__name__` representing the current file
app = Flask(__name__) 

app.config["SESSION_PERMANENT"] = False
Darren Christopher
  • 3,893
  • 4
  • 20
  • 37