Simplify caching for pygments styles

This commit is contained in:
Jake Howard 2022-08-20 18:32:25 +01:00
parent fd445375ae
commit 900aaad850
Signed by: jake
GPG Key ID: 57AFB45680EDD477
2 changed files with 4 additions and 13 deletions

View File

@ -2,7 +2,7 @@ from django.test import TestCase
from django.urls import reverse from django.urls import reverse
from pygments.styles import get_all_styles from pygments.styles import get_all_styles
from .utils import PYGMENTS_VERSION, PYGMENTS_VERSION_SLUG from .utils import PYGMENTS_VERSION_SLUG
class PygmentsStylesTestCase(TestCase): class PygmentsStylesTestCase(TestCase):
@ -11,8 +11,7 @@ class PygmentsStylesTestCase(TestCase):
with self.subTest(style=style): with self.subTest(style=style):
response = self.client.get(reverse("code-block:styles", args=[style])) response = self.client.get(reverse("code-block:styles", args=[style]))
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response["Cache-Control"], "max-age=3600, public") self.assertEqual(response["Cache-Control"], "max-age=3600")
self.assertEqual(response["ETag"], f'"{PYGMENTS_VERSION}"')
def test_unknown_style(self) -> None: def test_unknown_style(self) -> None:
response = self.client.get(reverse("code-block:styles", args=["not-a-style"])) response = self.client.get(reverse("code-block:styles", args=["not-a-style"]))

View File

@ -1,18 +1,10 @@
from django.http import Http404, HttpRequest, HttpResponse from django.http import Http404, HttpRequest, HttpResponse
from django.views.decorators.cache import cache_control from django.views.decorators.cache import cache_page
from django.views.decorators.http import etag
from pygments.formatters.html import HtmlFormatter from pygments.formatters.html import HtmlFormatter
from pygments.util import ClassNotFound from pygments.util import ClassNotFound
from .utils import PYGMENTS_VERSION
@cache_page(3600)
def pygments_etag(request: HttpRequest, name: str) -> str:
return PYGMENTS_VERSION
@etag(pygments_etag)
@cache_control(max_age=3600, public=True)
def pygments_styles(request: HttpRequest, name: str) -> HttpResponse: def pygments_styles(request: HttpRequest, name: str) -> HttpResponse:
try: try:
formatter = HtmlFormatter(style=name) formatter = HtmlFormatter(style=name)