Skip to content

Commit 87c6325

Browse files
committed
news: cache the news details page for non-logged in users
Logged in users can edit the page so the content should not be cached, for non-logged in users we are happy to cache this page in nginx.
1 parent b8a6a36 commit 87c6325

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

main/utils.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import hashlib
22
import pickle
33
import re
4+
from functools import WRAPPER_ASSIGNMENTS, wraps
45

56
import markdown
67
from django.core.cache import cache
78
from django.db import connections, router
89
from django.http import HttpResponse
910
from django.template.defaultfilters import slugify
1011
from django.utils.timezone import now
12+
from django.views.decorators.cache import cache_page
1113
from markdown.extensions import Extension
1214
from pgpdump.packet import SignaturePacket
1315

@@ -62,6 +64,22 @@ def empty_response():
6264
make_choice = lambda l: [(str(m), str(m)) for m in l] # noqa E741
6365

6466

67+
def cache_user_page(timeout):
68+
'''Cache the page only for non-logged in users'''
69+
70+
def decorator(view_func):
71+
@wraps(view_func, assigned=WRAPPER_ASSIGNMENTS)
72+
def _wrapped_view(request, *args, **kwargs):
73+
if request.user.is_authenticated:
74+
return view_func(request, *args, **kwargs)
75+
result = cache_page(
76+
timeout,
77+
key_prefix=(f"_auth_{request.user.is_authenticated}_"))
78+
return result(view_func)(request, *args, **kwargs)
79+
return _wrapped_view
80+
return decorator
81+
82+
6583
def set_created_field(sender, **kwargs):
6684
'''This will set the 'created' field on any object to the current UTC time
6785
if it is unset.

news/urls.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from django.contrib.auth.decorators import permission_required
22
from django.urls import path, re_path
33

4+
from main.utils import cache_user_page
5+
46
from .views import (
57
NewsCreateView,
68
NewsDeleteView,
@@ -21,7 +23,7 @@
2123
path('add/',
2224
permission_required('news.add_news')(NewsCreateView.as_view())),
2325
re_path(r'^(?P<slug>[-\w]+)/$',
24-
NewsDetailView.as_view()),
26+
cache_user_page(317)(NewsDetailView.as_view())),
2527
re_path(r'^(?P<slug>[-\w]+)/edit/$',
2628
permission_required('news.change_news')(NewsEditView.as_view())),
2729
re_path(r'^(?P<slug>[-\w]+)/delete/$',

0 commit comments

Comments
 (0)