Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete session key from all users

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?

like image 355
Mikael Avatar asked Jun 16 '15 10:06

Mikael


2 Answers

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

like image 191
e4c5 Avatar answered Oct 22 '22 23:10

e4c5


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()
like image 44
garnertb Avatar answered Oct 22 '22 23:10

garnertb