Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache public site pages and Apply homepage #1160

Merged
merged 6 commits into from
Apr 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions opentech/apply/home/models.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
from django.conf import settings
from django.db import models
from django.utils.decorators import method_decorator

from wagtail.admin.edit_handlers import FieldPanel
from wagtail.core.models import Page
from wagtail.search import index

from django.db import models
from wagtailcache.cache import cache_page, WagtailCacheMixin

from opentech.apply.funds.models import ApplicationBase, LabBase


class ApplyHomePage(Page):
@method_decorator(cache_page, name='serve')
class ApplyHomePage(WagtailCacheMixin, Page):
# Only allow creating HomePages at the root level
parent_page_types = ['wagtailcore.Page']
subpage_types = ['funds.FundType', 'funds.LabType', 'funds.RequestForPartners']
Expand All @@ -22,6 +27,9 @@ class ApplyHomePage(Page):
FieldPanel('strapline'),
]

def cache_control(self):
return f'public, s-maxage={settings.CACHE_CONTROL_S_MAXAGE}'

def get_context(self, *args, **kwargs):
context = super().get_context(*args, **kwargs)
context['open_funds'] = ApplicationBase.objects.order_by_end_date().prefetch_related(
Expand Down
10 changes: 9 additions & 1 deletion opentech/public/utils/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from django.core.exceptions import ValidationError
from django.conf import settings
from django.db import models
from django.utils.decorators import method_decorator

from wagtail.admin.edit_handlers import (
FieldPanel,
Expand All @@ -16,6 +18,8 @@
from wagtail.snippets.models import register_snippet
from wagtail.contrib.settings.models import BaseSetting, register_setting

from wagtailcache.cache import cache_page, WagtailCacheMixin


class LinkFields(models.Model):
"""
Expand Down Expand Up @@ -242,7 +246,8 @@ class Meta:
]


class BasePage(SocialFields, ListingFields, Page):
@method_decorator(cache_page, name='serve')
class BasePage(WagtailCacheMixin, SocialFields, ListingFields, Page):
show_in_menus_default = True

header_image = models.ForeignKey(
Expand All @@ -266,6 +271,9 @@ class Meta:
ListingFields.promote_panels
)

def cache_control(self):
return f'public, s-maxage={settings.CACHE_CONTROL_S_MAXAGE}'


class BaseFunding(Orderable):
value = models.PositiveIntegerField()
Expand Down
9 changes: 9 additions & 0 deletions opentech/public/utils/wagtail_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from wagtail.contrib.modeladmin.options import ModelAdminGroup, ModelAdmin, modeladmin_register
from wagtail.core import hooks

from wagtailcache.cache import clear_cache

from opentech.public.news.models import NewsType
from opentech.public.people.models import PersonType

Expand Down Expand Up @@ -31,3 +33,10 @@ def editor_css():
link = '<link rel="stylesheet" href="{}">\n'
path = static('css/apply/wagtail_editor.css')
return link.format(path)


@hooks.register('after_create_page')
@hooks.register('after_edit_page')
def clear_wagtailcache(request, page):
if page.live:
clear_cache()
60 changes: 41 additions & 19 deletions opentech/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@
'django_fsm',
'django_pwned_passwords',
'rest_framework',
'wagtailcache',

'hijack',
'compat',
Expand Down Expand Up @@ -197,28 +198,62 @@


# Cache

# Set max-age header.
try:
CACHE_CONTROL_MAX_AGE = int(env.get('CACHE_CONTROL_MAX_AGE', 3600))
except ValueError:
CACHE_CONTROL_MAX_AGE = 3600

# Set s-max-age header that is used by reverse proxy/front end cache.
try:
CACHE_CONTROL_S_MAXAGE = int(env.get('CACHE_CONTROL_S_MAXAGE', 3600))
except ValueError:
CACHE_CONTROL_S_MAXAGE = 3600

# Set wagtail cache timeout (automatic cache refresh).
WAGTAIL_CACHE_TIMEOUT = CACHE_CONTROL_MAX_AGE

if 'REDIS_URL' in env:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": env['REDIS_URL'],
},
"wagtailcache": {
"BACKEND": "wagtailcache.compat_backends.django_redis.RedisCache",
"LOCATION": env['REDIS_URL'],
'KEY_PREFIX': 'wagtailcache',
'TIMEOUT': WAGTAIL_CACHE_TIMEOUT,
}
}
else:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'database_cache',
},
'wagtailcache': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'database_cache',
'KEY_PREFIX': 'wagtailcache',
'TIMEOUT': WAGTAIL_CACHE_TIMEOUT,
}
}

WAGTAIL_CACHE_BACKEND = 'wagtailcache'

# Set s-max-age header that is used by reverse proxy/front end cache. See
# urls.py
try:
CACHE_CONTROL_S_MAXAGE = int(env.get('CACHE_CONTROL_S_MAXAGE', 600))
except ValueError:
pass
# Cloudflare cache
if 'CLOUDFLARE_API_TOKEN' in env:
INSTALLED_APPS += ('wagtail.contrib.frontend_cache', ) # noqa
WAGTAILFRONTENDCACHE = {
'cloudflare': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.CloudflareBackend',
'EMAIL': env['CLOUDFLARE_API_EMAIL'],
'TOKEN': env['CLOUDFLARE_API_TOKEN'],
'ZONEID': env['CLOUDFLARE_API_ZONEID'],
},
}


# Search
Expand Down Expand Up @@ -568,19 +603,6 @@
)


# Cloudflare cache
if 'CLOUDFLARE_API_TOKEN' in env:
INSTALLED_APPS += ('wagtail.contrib.frontend_cache', ) # noqa
WAGTAILFRONTENDCACHE = {
'cloudflare': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.CloudflareBackend',
'EMAIL': env['CLOUDFLARE_API_EMAIL'],
'TOKEN': env['CLOUDFLARE_API_TOKEN'],
'ZONEID': env['CLOUDFLARE_API_ZONEID'],
},
}


if 'PRIMARY_HOST' in env:
# This is used by Wagtail's email notifications for constructing absolute
# URLs.
Expand Down
2 changes: 2 additions & 0 deletions opentech/settings/dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGEME!!!'

WAGTAIL_CACHE = False

INTERNAL_IPS = ('127.0.0.1', '10.0.2.2')

ALLOWED_HOSTS = ['apply.localhost', 'localhost', '127.0.0.1', 'dev.otf.is', 'dev-apply.otf.is']
Expand Down
3 changes: 3 additions & 0 deletions opentech/settings/local.py.example
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,6 @@ CACHES = {
# BASE_URL = 'http://otf.test'

# SECRET_KEY = 'CHANGEME!!!'

# Enable Wagtail Cache while developing
# WAGTAIL_CACHE = True
17 changes: 0 additions & 17 deletions opentech/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
from django.conf import settings
from django.urls import include, path
from django.contrib import admin
from django.views.decorators.cache import cache_control
from django.views.generic import TemplateView
from django.conf.urls import url

from wagtail.utils.urlpatterns import decorate_urlpatterns
from wagtail.contrib.sitemaps.views import sitemap
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wagtail_urls
Expand All @@ -16,19 +14,6 @@
from opentech.apply.users.urls import public_urlpatterns as user_urls


def apply_cache_control(*patterns):
# Cache-control
cache_length = getattr(settings, 'CACHE_CONTROL_MAX_AGE', None)

if cache_length:
patterns = decorate_urlpatterns(
patterns,
cache_control(max_age=cache_length)
)

return list(patterns)


urlpatterns = [
path('django-admin/', admin.site.urls),
path('admin/', include(wagtailadmin_urls)),
Expand Down Expand Up @@ -71,8 +56,6 @@ def apply_cache_control(*patterns):
path('', include(wagtail_urls)),
]

urlpatterns = apply_cache_control(*urlpatterns)


if settings.DEBUG and settings.DEBUGTOOLBAR:
import debug_toolbar
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,5 @@ Pillow==4.3.0
psycopg2==2.7.3.1
social_auth_app_django==3.1.0
wagtail~=2.2.0
wagtail-cache==0.5.1
whitenoise==4.0