4

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!

user2662692
  • 227
  • 5
  • 15
  • 3
    Your best bet is to run a celery task every X minutes that checks the session database to see which sessions have become expired. You could use the [`user_logged_out`](https://docs.djangoproject.com/en/1.4/topics/auth/#django.contrib.auth.django.contrib.auth.signals.user_logged_out) signal but that will obviously only work when a user expires their session manually by logging out, it won't work for sessions that expire due to inactivity – Timmy O'Mahony Feb 06 '15 at 19:46

1 Answers1

5

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!

Community
  • 1
  • 1
Jackall
  • 1,120
  • 1
  • 9
  • 18
  • 1
    For those that find this while Googling like I did, bear in mind that subclassing a custom middleware from object no longer works in Django 1.10+, via [this question](https://stackoverflow.com/questions/39457381/object-takes-no-parameters-in-django-1-10?noredirect=1&lq=1) – gallen May 28 '18 at 18:14