3

I wonder how I could trigger an action whenever a session timeout occurs. Is there a way to set up a callback function that would be executed before the session data get destroyed? I need a solution that also works for unauthenticated users.

Buddyshot
  • 1,614
  • 1
  • 17
  • 44

1 Answers1

0

Assuming that you are using the default session database backend, you can use a Django signal to detect when a session is deleted from the DB, following an approach similar to this:

Django - detect session start and end

Note that in Django 1.5+ the command to use is clearsessions, and not cleanup.

For more details you can refer to the official documentation on clearing the session store.

If the cronjob configuration is not feasible in your case, you can also clear the session store in one of your views, by doing something like this:

from django.core import management
management.call_command('clearsessions')
Community
  • 1
  • 1
Augusto Destrero
  • 4,095
  • 1
  • 23
  • 25
  • The thing is I'm not interested in cleaning up the `Session` table. As mentioned in the documentation, this can be done with a cron job. What I want to do is to have a **trigger** that gets activated whenever a session `s` arrives to a point where `s.expire_date - timezone.now() < 0`. Sadly it does not seem to be as straighforward as I thought, so I think I will go with a Celery task that checks every 2min whether `Session.objects.filter(expire_data__lt=timezone.now())` returns something, then process the data and finally make a `clearsessions`. – Buddyshot Nov 26 '14 at 13:19
  • Using the pre_delete signal on Session model let you act immediately on users that perform an explicit logout (without even waiting two minutes). Clearing the session store with a cron job (or even with a Celery task) let you delete expired Session objects for users who did not logout explicitly (e.g. closing the browser), activating again the pre_delete signal. – Augusto Destrero Nov 26 '14 at 14:01
  • I am precisely interested in getting noticed of the sessions that have expired but that were not explicitly deleted by a user logout. Thus writing a Celery task that does both (filtering expired session, process the data and cleanup the table) is easier to maintain IMHO. I mean, `pre_delete` is not gonna get triggered unless I ask to. – Buddyshot Nov 26 '14 at 14:28
  • 1
    Ok. Now I see your point. I think the celery task that periodically check the session store is the best solution. – Augusto Destrero Nov 26 '14 at 14:31