From eef673db2fdea4dec2959d8b68dcd0e9910547b0 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Sun, 31 Mar 2024 15:02:48 +0100 Subject: [PATCH] Cache page templates --- yamdl_playground/core/models.py | 10 ++++++++++ yamdl_playground/core/views.py | 6 ++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/yamdl_playground/core/models.py b/yamdl_playground/core/models.py index b4ea30d..c16c2e5 100644 --- a/yamdl_playground/core/models.py +++ b/yamdl_playground/core/models.py @@ -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 diff --git a/yamdl_playground/core/views.py b/yamdl_playground/core/views.py index 238c736..ee513ee 100644 --- a/yamdl_playground/core/views.py +++ b/yamdl_playground/core/views.py @@ -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})) })