From aaf0bb4571a487007b7d21dbd1d18b1739dcb921 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Sun, 24 Mar 2024 18:36:48 +0000 Subject: [PATCH] Improve markdown rendering performance Reuse the markdown instance and cache data --- .gitignore | 2 ++ yamdl_playground/core/views.py | 14 +++++++++++++- yamdl_playground/settings.py | 7 +++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index ad4a1f1..dfb652b 100644 --- a/.gitignore +++ b/.gitignore @@ -174,3 +174,5 @@ poetry.toml pyrightconfig.json # End of https://www.toptal.com/developers/gitignore/api/python + +cache/ diff --git a/yamdl_playground/core/views.py b/yamdl_playground/core/views.py index 34ccc14..f74416f 100644 --- a/yamdl_playground/core/views.py +++ b/yamdl_playground/core/views.py @@ -3,6 +3,11 @@ from django.http import HttpResponse from django.db import connections from django.shortcuts import get_object_or_404 import markdown +from django.core.cache import caches +from threading import Lock + +md = markdown.Markdown() +md_lock = Lock() def search(request): with connections["default"].cursor() as cursor: @@ -11,7 +16,14 @@ def search(request): pages = Page.objects.filter(id__in=row) return HttpResponse(str(pages), content_type="text/plain") + def content(request, slug): page = get_object_or_404(Page, slug=slug) - return HttpResponse(markdown.markdown(page.content), content_type="text/html") + if (cached_content := caches["default"].get(f"page-content-{slug}")) is None: + with md_lock: + cached_content = md.convert(page.content) + md.reset() + caches["default"].set(f"page-content-{slug}", cached_content) + + return HttpResponse(cached_content, content_type="text/html") diff --git a/yamdl_playground/settings.py b/yamdl_playground/settings.py index 0826c55..ac7f2da 100644 --- a/yamdl_playground/settings.py +++ b/yamdl_playground/settings.py @@ -84,6 +84,13 @@ YAMDL_DIRECTORIES = [ YAMDL_LOADER = "yamdl_playground.core.utils.CustomYamdlLoader" +CACHES = { + "default": { + "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", + "LOCATION": BASE_DIR / "cache", + } +} + # Password validation # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators