Delete session key from all users

佐手、 提交于 2019-12-17 19:39:48

问题


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?


回答1:


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




回答2:


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()



回答3:


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?



来源:https://stackoverflow.com/questions/30864711/delete-session-key-from-all-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!