clear_cache.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # -*- coding: utf-8 -*-
  2. # Author: AxiaCore S.A.S. http://axiacore.com
  3. from django.conf import settings
  4. from django.core.cache import DEFAULT_CACHE_ALIAS, caches
  5. from django.core.cache.backends.base import InvalidCacheBackendError
  6. from django.core.management.base import BaseCommand, CommandError
  7. from django_extensions.management.utils import signalcommand
  8. class Command(BaseCommand):
  9. """A simple management command which clears the site-wide cache."""
  10. help = 'Fully clear site-wide cache.'
  11. def add_arguments(self, parser):
  12. parser.add_argument('--cache', action='append',
  13. help='Name of cache to clear')
  14. parser.add_argument('--all', '-a', action='store_true', default=False,
  15. dest='all_caches', help='Clear all configured caches')
  16. @signalcommand
  17. def handle(self, cache, all_caches, *args, **kwargs):
  18. if not cache and not all_caches:
  19. cache = [DEFAULT_CACHE_ALIAS]
  20. elif cache and all_caches:
  21. raise CommandError('Using both --all and --cache is not supported')
  22. elif all_caches:
  23. cache = getattr(settings, 'CACHES', {DEFAULT_CACHE_ALIAS: {}}).keys()
  24. for key in cache:
  25. try:
  26. caches[key].clear()
  27. except InvalidCacheBackendError:
  28. self.stderr.write('Cache "%s" is invalid!\n' % key)
  29. else:
  30. self.stdout.write('Cache "%s" has been cleared!\n' % key)