Coverage for apps / core / management / commands / cleanup_sessions.py: 47%

17 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-04-12 10:49 +0000

1"""Management command to clean up expired sessions with run tracking.""" 

2 

3from django.contrib.sessions.models import Session 

4from django.core.cache import cache 

5from django.core.management.base import BaseCommand 

6from django.utils import timezone 

7 

8CLEANUP_CACHE_KEY = "session_cleanup_last_run" 

9 

10 

11class Command(BaseCommand): 

12 help = "Delete expired sessions and record run stats" 

13 

14 def handle(self, *args, **options): 

15 now = timezone.now() 

16 expired = Session.objects.filter(expire_date__lt=now) 

17 count = expired.count() 

18 expired.delete() 

19 remaining = Session.objects.count() 

20 

21 cache.set( 

22 CLEANUP_CACHE_KEY, 

23 {"time": now.isoformat(), "deleted": count, "remaining": remaining}, 

24 timeout=None, 

25 ) 

26 

27 if count: 

28 self.stdout.write(f"Deleted {count} expired sessions.") 

29 else: 

30 self.stdout.write("No expired sessions to clean up.") 

← Back to Dashboard