Skip to content

Commit 43430a5

Browse files
authored
add configurable global Surrogate-Key header (#1506)
This will allow us to safely purge Django pages from the CDN without causing expensive large files like binary and tarball artifacts from being purged as well.
1 parent d04c7a2 commit 43430a5

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

pydotorg/middleware.py

+24-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
from django.conf import settings
2+
3+
14
class AdminNoCaching:
25
"""
36
Middleware to ensure the admin is not cached by Fastly or other caches
@@ -8,6 +11,25 @@ def __init__(self, get_response):
811

912
def __call__(self, request):
1013
response = self.get_response(request)
11-
if request.path.startswith('/admin'):
12-
response['Cache-Control'] = 'private'
14+
if request.path.startswith("/admin"):
15+
response["Cache-Control"] = "private"
16+
return response
17+
18+
19+
class GlobalSurrogateKey:
20+
"""
21+
Middleware to insert a Surrogate-Key for purging in Fastly or other caches
22+
"""
23+
24+
def __init__(self, get_response):
25+
self.get_response = get_response
26+
27+
def __call__(self, request):
28+
response = self.get_response(request)
29+
if hasattr(settings, "GLOBAL_SURROGATE_KEY"):
30+
response["Surrogate-Key"] = " ".join(
31+
filter(
32+
None, [settings.GLOBAL_SURROGATE_KEY, response.get("Surrogate-Key")]
33+
)
34+
)
1335
return response

pydotorg/settings/base.py

+5
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@
118118
'django.middleware.common.CommonMiddleware',
119119
'django.middleware.csrf.CsrfViewMiddleware',
120120
'pydotorg.middleware.AdminNoCaching',
121+
'pydotorg.middleware.GlobalSurrogateKey',
121122
'django.contrib.auth.middleware.AuthenticationMiddleware',
122123
'django.contrib.messages.middleware.MessageMiddleware',
123124
'waffle.middleware.WaffleMiddleware',
@@ -281,3 +282,7 @@
281282
'user': '1000/day',
282283
},
283284
}
285+
286+
### pydotorg.middleware.GlobalSurrogateKey
287+
288+
GLOBAL_SURROGATE_KEY = 'pydotorg-app'

0 commit comments

Comments
 (0)