Most optimized way to delete all sessions for a specific user in Django?

后端 未结 5 1381
感动是毒
感动是毒 2021-02-01 18:40

I\'m running Django 1.3, using Sessions Middleware and Auth Middleware:

# settings.py

SESSION_ENGINE = django.contrib.sessions.backends.db   # Persist sessions          


        
5条回答
  •  轮回少年
    2021-02-01 18:57

    Another version of a function using list comprehension that will just straight up delete every unexpired session of a user:

    from django.utils import timezone
    from django.contrib.sessions.models import Session
    
    
    def delete_all_unexpired_sessions_for_user(user):
        unexpired_sessions = Session.objects.filter(expire_date__gte=timezone.now())
        [
            session.delete() for session in unexpired_sessions
            if str(user.pk) == session.get_decoded().get('_auth_user_id')
        ]
    

提交回复
热议问题