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?
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.
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.
You could also use ./manage.py clearsessions
to clean up expired sessions. Unexpired ones will be retained.
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With