|
| 1 | +"""Clear all configured Django cache backends.""" |
| 2 | + |
| 3 | +from django.conf import settings |
| 4 | +from django.core.cache import caches |
| 5 | +from django.core.management.base import BaseCommand |
| 6 | + |
| 7 | + |
| 8 | +class Command(BaseCommand): |
| 9 | + help = ( |
| 10 | + "Clear all configured Django cache backends. " |
| 11 | + "Iterates over every backend in settings.CACHES (not just 'default'), " |
| 12 | + "so separate session, view, and custom caches are all flushed." |
| 13 | + ) |
| 14 | + |
| 15 | + def handle(self, *args, **options): |
| 16 | + cache_aliases = list(settings.CACHES.keys()) |
| 17 | + |
| 18 | + if not cache_aliases: |
| 19 | + self.stdout.write("No caches configured in settings.CACHES.") |
| 20 | + return |
| 21 | + |
| 22 | + self.stdout.write( |
| 23 | + f"Clearing {len(cache_aliases)} cache backend(s):" |
| 24 | + f" {', '.join(cache_aliases)}\n" |
| 25 | + ) |
| 26 | + |
| 27 | + cleared, failed = 0, 0 |
| 28 | + for alias in cache_aliases: |
| 29 | + backend = settings.CACHES[alias].get("BACKEND", "unknown backend") |
| 30 | + try: |
| 31 | + caches[alias].clear() |
| 32 | + cleared += 1 |
| 33 | + self.stdout.write(self.style.SUCCESS(f" {alias:<15} ({backend})")) |
| 34 | + except Exception as exc: |
| 35 | + failed += 1 |
| 36 | + self.stderr.write( |
| 37 | + self.style.ERROR( |
| 38 | + f" {alias:<15} ({backend})" |
| 39 | + f" -- {exc.__class__.__name__}: {exc}" |
| 40 | + ) |
| 41 | + ) |
| 42 | + |
| 43 | + summary = f"\nDone. Cleared {cleared}, failed {failed}." |
| 44 | + if failed: |
| 45 | + self.stderr.write(self.style.WARNING(summary)) |
| 46 | + else: |
| 47 | + self.stdout.write(summary) |
0 commit comments