Skip to content

Commit

Permalink
news: cache the news details page for non-logged in users
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jelly committed Jul 20, 2024
1 parent 863cf78 commit 8402ce6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
18 changes: 18 additions & 0 deletions main/utils.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import hashlib
import pickle
import re
from functools import WRAPPER_ASSIGNMENTS, wraps

import markdown
from django.core.cache import cache
from django.db import connections, router
from django.http import HttpResponse
from django.template.defaultfilters import slugify
from django.utils.timezone import now
from django.views.decorators.cache import cache_page
from markdown.extensions import Extension
from pgpdump.packet import SignaturePacket

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


def cache_user_page(timeout):
'''Cache the page only for non-logged in users'''

def decorator(view_func):
@wraps(view_func, assigned=WRAPPER_ASSIGNMENTS)
def _wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated:
return view_func(request, *args, **kwargs)
result = cache_page(
timeout,
key_prefix=(f"_auth_{request.user.is_authenticated}_"))
return result(view_func)(request, *args, **kwargs)
return _wrapped_view
return decorator


def set_created_field(sender, **kwargs):
'''This will set the 'created' field on any object to the current UTC time
if it is unset.
Expand Down
4 changes: 3 additions & 1 deletion news/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from django.contrib.auth.decorators import permission_required
from django.urls import path, re_path

from main.utils import cache_user_page

from .views import (
NewsCreateView,
NewsDeleteView,
Expand All @@ -21,7 +23,7 @@
path('add/',
permission_required('news.add_news')(NewsCreateView.as_view())),
re_path(r'^(?P<slug>[-\w]+)/$',
NewsDetailView.as_view()),
cache_user_page(1831)(NewsDetailView.as_view())),
re_path(r'^(?P<slug>[-\w]+)/edit/$',
permission_required('news.change_news')(NewsEditView.as_view())),
re_path(r'^(?P<slug>[-\w]+)/delete/$',
Expand Down

0 comments on commit 8402ce6

Please sign in to comment.