Skip to content

Commit 8df7724

Browse files
committed
Purge Fastly on Page Save
- Fixes #480 - Is a NOOP if DEBUG=True or FASTLY_API_KEY does not exist - Will create infrastructure ticket to set key in production
1 parent aa79103 commit 8df7724

File tree

4 files changed

+37
-0
lines changed

4 files changed

+37
-0
lines changed

fastly/__init__.py

Whitespace-only changes.

fastly/models.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Intentionally left blank

fastly/utils.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import requests
2+
3+
from django.conf import settings
4+
5+
6+
def purge_url(path):
7+
"""
8+
Purge a Fastly.com URL given a path. path argument must begin with a slash
9+
"""
10+
if settings.DEBUG:
11+
return
12+
13+
api_key = getattr(settings, 'FASTLY_API_KEY', None)
14+
if api_key:
15+
response = requests.request(
16+
'PURGE',
17+
'https://www.python.org{}'.format(path),
18+
headers={'Fastly-Key': api_key},
19+
)
20+
return response
21+
22+
return None

pages/models.py

+14
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,16 @@
88

99
import os
1010
import re
11+
1112
from django.conf import settings
1213
from django.core import validators
1314
from django.db import models
15+
from django.db.models.signals import post_save
16+
from django.dispatch import receiver
17+
1418
from markupfield.fields import MarkupField
1519
from cms.models import ContentManageable
20+
from fastly.utils import purge_url
1621
from .managers import PageManager
1722

1823
DEFAULT_MARKUP_TYPE = getattr(settings, 'DEFAULT_MARKUP_TYPE', 'restructuredtext')
@@ -73,6 +78,15 @@ def get_absolute_url(self):
7378
return "/{}/".format(self.path)
7479

7580

81+
@receiver(post_save, sender=Page)
82+
def purge_fastly_cache(sender, instance, **kwargs):
83+
"""
84+
Purge fastly.com cache if in production and the page is published.
85+
Requires settings.FASTLY_API_KEY being set
86+
"""
87+
purge_url('/{}'.format(instance.path))
88+
89+
7690
def page_image_path(instance, filename):
7791
return os.path.join(settings.MEDIA_ROOT, instance.page.path, filename)
7892

0 commit comments

Comments
 (0)