-
-
Notifications
You must be signed in to change notification settings - Fork 673
Expand file tree
/
Copy pathmiddleware.py
More file actions
62 lines (47 loc) · 1.68 KB
/
middleware.py
File metadata and controls
62 lines (47 loc) · 1.68 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
from django.conf import settings
class AdminNoCaching:
"""
Middleware to ensure the admin is not cached by Fastly or other caches
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if request.path.startswith("/admin"):
response["Cache-Control"] = "private"
return response
class GlobalSurrogateKey:
"""
Middleware to insert a Surrogate-Key for purging in Fastly or other caches.
Adds both a global key (for full site purges) and section-based keys
derived from the URL path (for targeted purges like /downloads/).
"""
def __init__(self, get_response):
self.get_response = get_response
def _get_section_key(self, path):
"""
Extract section surrogate key from URL path.
Examples:
/downloads/ -> downloads
/downloads/release/python-3141/ -> downloads
/events/python-events/ -> events
/ -> None
"""
parts = path.strip("/").split("/")
if parts and parts[0]:
return parts[0]
return None
def __call__(self, request):
response = self.get_response(request)
keys = []
if hasattr(settings, "GLOBAL_SURROGATE_KEY"):
keys.append(settings.GLOBAL_SURROGATE_KEY)
section_key = self._get_section_key(request.path)
if section_key:
keys.append(section_key)
existing = response.get("Surrogate-Key")
if existing:
keys.append(existing)
if keys:
response["Surrogate-Key"] = " ".join(keys)
return response