-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Expand file tree
/
Copy pathclear_cache.py
More file actions
63 lines (53 loc) 路 2.36 KB
/
Copy pathclear_cache.py
File metadata and controls
63 lines (53 loc) 路 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# Copyright (c) 2023-present Plane Software, Inc. and contributors
# SPDX-License-Identifier: AGPL-3.0-only
# See the LICENSE file for details.
# Django imports
from django.conf import settings
from django.core.cache import cache
from django.core.management import BaseCommand
class Command(BaseCommand):
help = "Clear Cache before starting the server to remove stale values"
def add_arguments(self, parser):
# Positional argument
parser.add_argument("--key", type=str, nargs="?", help="Key to clear cache")
parser.add_argument(
"--all",
action="store_true",
help="Flush the entire cache database (FLUSHDB) instead of only scoped prefix keys",
)
def handle(self, *args, **options):
try:
if options.get("key"):
cache.delete(options["key"])
self.stdout.write(self.style.SUCCESS(f"Cache Cleared for key: {options['key']}"))
return
# If user explicitly requests flushing the entire DB
if options.get("all"):
cache.clear()
self.stdout.write(self.style.SUCCESS("Entire cache database cleared (FLUSHDB)"))
return
# Scoped cache clear using KEY_PREFIX
key_prefix = getattr(cache, "key_prefix", None) or getattr(settings, "REDIS_KEY_PREFIX", None)
if not key_prefix:
self.stdout.write(
self.style.ERROR(
"Cannot clear cache: KEY_PREFIX is not configured. "
"Use --all if you explicitly wish to flush the entire database."
)
)
return
if not hasattr(cache, "delete_pattern"):
self.stdout.write(
self.style.ERROR(
"Cannot clear cache: Cache backend does not support delete_pattern(). "
"Use --all if you explicitly wish to flush the entire database."
)
)
return
pattern = f"{key_prefix}:*"
cache.delete_pattern(pattern)
self.stdout.write(self.style.SUCCESS(f"Cache Cleared for pattern: {pattern}"))
return
except Exception as e:
self.stdout.write(self.style.ERROR(f"Failed to clear cache: {e}"))
return