Cristian
Cristian

Reputation: 495

How to run a function on session ends in Flask?

I want to be a able to run a function once a user's session ends( they either close the browser or it times out).

How would I go about doing this?

#create timeout
@app.before_request
def make_session_permanent():
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=5)

#run function once session ends
#@app.session_ends
def session_ended()
    #run code

Upvotes: 5

Views: 4851

Answers (3)

Andreas
Andreas

Reputation: 8019

Due to the way HTTP sessions work, there is simply no reliable way to do this.

Think more about what problem you're trying to solve and find another way to do it than running a function when a session expires.

Upvotes: 2

Ganesh Shenoy
Ganesh Shenoy

Reputation: 629

I guess the flask is cookie based, and you don't have a callback option available. But if of help following are some pointers.

Call a function when Flask session expires

Catch session expiration in Flask

https://www.google.com/amp/s/pythonawesome.com/flask-user-session-management/amp/

Edit

One possibility could be to run some timer or scheduler, check and invalidate the session, would say kind of hack, not a clean solution.

Upvotes: 1

Govinda Malavipathirana
Govinda Malavipathirana

Reputation: 1141

In @app.before_request check whether session is globally active or not by using something like g. After that call for the action you need.

from flask import g

@app.before_request
def before_request():
    g.user = None
    if 'user' in session:
        g.user = session['user']
    else:
        session_ended()

Upvotes: 3

Related Questions