Delete session key from all users

前端 未结 3 1217
慢半拍i
慢半拍i 2020-12-10 15:23

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 al

相关标签:
3条回答
  • 2020-12-10 15:34

    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 讨论(0)
  • 2020-12-10 15:44

    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?

    0 讨论(0)
  • 2020-12-10 15:54

    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 讨论(0)
提交回复
热议问题