1
Fork 0
yamdl-playground/yamdl_playground/core/views.py
Jake Howard aaf0bb4571
Improve markdown rendering performance
Reuse the markdown instance and cache data
2024-03-24 18:36:48 +00:00

29 lines
969 B
Python

from .models import Page
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:
cursor.execute("SELECT rowid FROM search_index WHERE search_index = %s;", ["content"])
row = cursor.fetchone()
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)
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")