Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing sessions in django_session table without logging out current users

Tags:

python

django

I am working on sessions in Django.

By default, django stores sessions in django_session, I found out there is no way to purge sessions.

Though clearsessions can be used to delete rows. It is also recommended to run this as a cron job. But doing this means logging out all logged-in users, right?

Is this the right way to do it?

like image 301
sachsure Avatar asked Aug 03 '16 20:08

sachsure


2 Answers

  1. Django 1.6 or Above

    python manage.py clearsessions

  2. Django 1.5 or lower

    python manage.py cleanup

  3. From Django Shell

    from django.contrib.sessions.models import Session
    Session.objects.all().delete()
    
  4. django-session-cleanup cronJob

  5. clearing session in logout( based on session key present in request)

from django.contrib.sessions.models import Session  
session_key = request.data['sessionKey']
session = Session.objects.get(session_key=session_key)
Session.objects.filter(session_key=session).delete()
Session.objects.all().delete()
like image 128
Roshan Bagdiya Avatar answered Oct 31 '22 11:10

Roshan Bagdiya


The Django documentation states (emphasis from me):

Clearing the session store

As users create new sessions on your website, session data can accumulate in your session store. If you’re using the database backend, the django_session database table will grow. If you’re using the file backend, your temporary directory will contain an increasing number of files.

To understand this problem, consider what happens with the database backend. When a user logs in, Django adds a row to the django_session database table. Django updates this row each time the session data changes. If the user logs out manually, Django deletes the row. But if the user does not log out, the row never gets deleted. A similar process happens with the file backend.

Django does not provide automatic purging of expired sessions. Therefore, it’s your job to purge expired sessions on a regular basis. Django provides a clean-up management command for this purpose: clearsessions. It’s recommended to call this command on a regular basis, for example as a daily cron job.

Note that the cache backend isn’t vulnerable to this problem, because caches automatically delete stale data. Neither is the cookie backend, because the session data is stored by the users’ browsers.

Found this link in Abid A's answer.

The clearsessions command

Can be run as a cron job or directly to clean out expired sessions.

So it won't log off every user.

As mentioned by Kevin Christopher Henry in a comment and in the other possible duplicate of your question flagged by e4c5.

like image 18
Emile Bergeron Avatar answered Oct 31 '22 10:10

Emile Bergeron