1
Fork 0

Cache page templates

This commit is contained in:
Jake Howard 2024-03-31 15:02:48 +01:00
parent 79aab1e15e
commit eef673db2f
Signed by: jake
GPG key ID: 57AFB45680EDD477
2 changed files with 12 additions and 4 deletions

View file

@ -1,5 +1,7 @@
from django.db import models
import markdown
from django.template import Template
from django.utils.functional import cached_property
class Tag(models.Model):
__yamdl__ = True
@ -12,6 +14,8 @@ class Tag(models.Model):
class Page(models.Model):
__yamdl__ = True
_template_cache = {}
title = models.CharField(max_length=255)
raw_content = models.TextField()
@ -34,3 +38,9 @@ class Page(models.Model):
instance.tags.set(tags)
return instance
@cached_property
def content_template(self):
if (cached_template := self._template_cache.get(self.slug)) is None:
cached_template = self._template_cache[self.slug] = Template(self.content, name=self.slug)
return cached_template

View file

@ -2,7 +2,7 @@ from .models import Page
from django.http import HttpResponse
from django.db import connections
from django.shortcuts import get_object_or_404, render
from django.template import Template, Context
from django.template import Context
def search(request):
with connections["default"].cursor() as cursor:
@ -15,9 +15,7 @@ def search(request):
def content(request, slug):
page = get_object_or_404(Page, slug=slug)
template = Template(page.content)
return render(request, "content.html", {
"page": page,
"content": template.render(Context({"request": request, "page": page}))
"content": page.content_template.render(Context({"request": request, "page": page}))
})