Is there a way I can track the length of time a session exist in Django?
Is there a way I can have Django run a function when the session expires? This would allow me to do that.
Thanks!
Is there a way I can track the length of time a session exist in Django?
Is there a way I can have Django run a function when the session expires? This would allow me to do that.
Thanks!
As @TimmyO'Mahony has mentioned, you could use the user_logged_out
signal to handle session end due to logout.
You could use a middleware for handling session expiry due to inactivity. The middleware can look like:
import time
from django.contrib.auth import logout
SESSION_TIMEOUT = 5400 # 90 minutes
class HandleSessionExpiryMiddleware(object):
def process_request(self, request):
last_activity = request.session.get('last_activity')
now = time.time()
idle = now - last_activity if last_activity else 0
timeout = SESSION_TIMEOUT
if idle > timeout:
run_on_expiry()
logout(session)
else:
request.session['last_activity'] = now
idle = 0
def run_on_expiry(self):
# Custom code
Assuming the above code is in a file sessions/middleware.py
, you would need to add this middleware to MIDDLEWARE_CLASSES
in your settings.py
like:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'sessions.middleware.HandleSessionExpiryMiddleware',
...
)
Hope this helps!