Bake pygments version into style URL

It's a hack, but it does work
This commit is contained in:
Jake Howard 2022-06-28 22:59:17 +01:00
parent b6c87d9583
commit 2b39fb1b9a
Signed by: jake
GPG Key ID: 57AFB45680EDD477
4 changed files with 26 additions and 1 deletions

View File

@ -2,6 +2,8 @@ from django.test import TestCase
from django.urls import reverse
from pygments.styles import get_all_styles
from .utils import PYGMENTS_VERSION, PYGMENTS_VERSION_SLUG
class PygmentsStylesTestCase(TestCase):
def test_accessible(self) -> None:
@ -12,9 +14,16 @@ class PygmentsStylesTestCase(TestCase):
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response["Cache-Control"], "max-age=3600, public")
self.assertEqual(response["ETag"], f'"{PYGMENTS_VERSION}"')
def test_unknown_style(self) -> None:
response = self.client.get(
reverse("static-pygments:styles", args=["not-a-style"])
)
self.assertEqual(response.status_code, 404)
def test_url_contains_version(self) -> None:
for style in get_all_styles():
with self.subTest(style=style):
url = reverse("static-pygments:styles", args=[style])
self.assertIn(PYGMENTS_VERSION_SLUG, url)

View File

@ -1,7 +1,11 @@
from django.urls import path
from .utils import PYGMENTS_VERSION_SLUG
from .views import pygments_styles
app_name = "code_block"
urlpatterns = [path("<slug:name>.css", pygments_styles, name="styles")]
urlpatterns = [
# HACK: Bake the pygments version into the URL, without needing a custom method
path(f"<slug:name>.{PYGMENTS_VERSION_SLUG}.css", pygments_styles, name="styles")
]

View File

@ -0,0 +1,4 @@
from importlib.metadata import version
PYGMENTS_VERSION = version("pygments")
PYGMENTS_VERSION_SLUG = PYGMENTS_VERSION.replace(".", "-")

View File

@ -1,9 +1,17 @@
from django.http import Http404, HttpRequest, HttpResponse
from django.views.decorators.cache import cache_control
from django.views.decorators.http import etag
from pygments.formatters.html import HtmlFormatter
from pygments.util import ClassNotFound
from .utils import PYGMENTS_VERSION
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:
try: