Delete session key from all users

3.4k views Asked by At

When a user logs in some details are saved to the session, lets say using key='user_settings'

When some updates happens within the system I need to loop through all users and delete the 'user_settings' key from each users session. That way I will trigger loading the details fresh from the database.

How can I loop through all sessions and remove the key from each of the sessions?

3

There are 3 answers

0
garnertb On

You can access and update session data via the SessionStore object:

from django.contrib.sessions.models import Session, SessionStore

for session in Session.objects.all():
    store = SessionStore(session.session_key)
    del store['user_settings']
    store.save()
0
e4c5 On

Looping

Even if your site has only a few thousand users, you might find that the django_sessions table has a few million entries in it. This happens if the sessions haven't been cleaned up. If you loop through them and delete the session entries you will find the process to be very slow. Even 100 sessions would result in a 100 queries being executed.

Using the Session Model.

You can apply filters on django.contrib.sessions.models.Session just as you would on any other model. Thus the following query would clear out all the sessions in one go.

 from django.contrib.sessions.models import Session
 Session.objects.all().delete()

You could choose to leave out some users

 Session.objects.filter(session_key__in = [ ... ]).delete()

It does not involve a data retrieval or looping.

./manage.py

You could also use ./manage.py clearsessions to clean up expired sessions. Unexpired ones will be retained.

At the database level

Perhaps the fasted is to delete all the sessions is with an sql query. Where as retrieval and delete will be very very slow and involves millions of queries.

In the case of databases that support TRUNCATE

TRUNCATE django_session

For those that don't

DELETE FROM django_session

Lastly bear in mind that sessions do expire from time to time, so there isn't a lot of harm in clearing an entire session object instead of just deleting a specific key

0
Aditya Singh On

You can delete the key from the session like any other dictionary.

del request.session['your key']

for more info check this out

How do I delete a session key in Django after it is used once?