Skip to content

Commit 7f10a3e

Browse files
committed
Merge branch 'minify-response'
2 parents 9bef646 + b27acbe commit 7f10a3e

File tree

9 files changed

+112
-44
lines changed

9 files changed

+112
-44
lines changed

conftest.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ def pytest_configure():
3232
"SERIAL": {"ENABLED": True, "TIMEOUT": 5},
3333
"CACHE_ALIAS": "default",
3434
"APPS": ("unicorn",),
35+
"MINIFY_HTML": False,
3536
}
3637

3738
caches = {

django_unicorn/components/unicorn_template_response.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from bs4.element import Tag
99
from bs4.formatter import HTMLFormatter
1010

11+
from django_unicorn.settings import get_minify_html_enabled
1112
from django_unicorn.utils import sanitize_html
1213

1314
from ..decorators import timed
@@ -123,6 +124,15 @@ def render(self):
123124

124125
response.content = rendered_template
125126

127+
if get_minify_html_enabled():
128+
# Import here in case the minify extra was not installed
129+
from htmlmin import minify
130+
131+
minified_html = minify(response.content.decode())
132+
133+
if len(minified_html) < len(rendered_template):
134+
response.content = minified_html
135+
126136
return response
127137

128138
@staticmethod

django_unicorn/settings.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
1+
import logging
2+
13
from django.conf import settings
24

35

6+
logger = logging.getLogger(__name__)
7+
8+
49
SETTINGS_KEY = "UNICORN"
510
LEGACY_SETTINGS_KEY = f"DJANGO_{SETTINGS_KEY}"
611

@@ -53,3 +58,19 @@ def get_serial_timeout():
5358
Default serial timeout is 60 seconds.
5459
"""
5560
return get_serial_settings().get("TIMEOUT", 60)
61+
62+
63+
def get_minify_html_enabled():
64+
minify_html_enabled = get_setting("MINIFY_HTML", False)
65+
66+
if minify_html_enabled:
67+
try:
68+
import htmlmin
69+
except ModuleNotFoundError:
70+
logger.error(
71+
"MINIFY_HTML is `True`, but minify extra could not be imported. Install with `unicorn[minify]`."
72+
)
73+
74+
return False
75+
76+
return minify_html_enabled

django_unicorn/views/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -484,4 +484,4 @@ def message(request: HttpRequest, component_name: str = None) -> JsonResponse:
484484
component_request = ComponentRequest(request, component_name)
485485
json_result = _handle_component_request(request, component_request)
486486

487-
return JsonResponse(json_result)
487+
return JsonResponse(json_result, json_dumps_params={"separators": (",", ":")})

noxfile.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
@nox.parametrize("django", ["2.2", "3.0", "3.2"])
66
def tests(session, django):
77
session.install("poetry")
8-
session.run("poetry", "install")
8+
session.run("poetry", "install", "-E", "minify")
99
session.install(f"django=={django}")
1010
session.run("pytest", "-m", "not slow")
1111
session.run("pytest", "-m", "slow")

poetry.lock

Lines changed: 38 additions & 41 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ shortuuid = "^1.0.1"
2222
cachetools = "^4.1.1"
2323
dataclasses = {version = "^0.8.0", python = "<3.7"}
2424
decorator = "^4.4.2"
25+
htmlmin = { version = "^0.1.12", optional = true }
26+
27+
[tool.poetry.extras]
28+
minify = ["htmlmin"]
2529

2630
[tool.poetry.dev-dependencies]
2731
pytest = "^6.2"

tests/templatetags/test_unicorn_render.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,23 @@ def test_unicorn_render_component_one_script_tag(settings):
244244
assert len(re.findall('<script type="module"', html)) == 1
245245

246246

247+
def test_unicorn_render_component_minify_html(settings):
248+
settings.DEBUG = True
249+
settings.UNICORN["MINIFY_HTML"] = True
250+
token = Token(
251+
TokenType.TEXT,
252+
"unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs'",
253+
)
254+
unicorn_node = unicorn(Parser([]), token)
255+
context = {}
256+
html = unicorn_node.render(Context(context))
257+
258+
assert "<script type=module" in html
259+
assert len(re.findall("<script type=module", html)) == 1
260+
261+
settings.UNICORN["MINIFY_HTML"] = False
262+
263+
247264
def test_unicorn_render_child_component_no_script_tag(settings):
248265
settings.DEBUG = True
249266
token = Token(

tests/test_settings.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
from django_unicorn.settings import get_cache_alias, get_serial_enabled, get_settings
1+
from django_unicorn.settings import (
2+
get_cache_alias,
3+
get_minify_html_enabled,
4+
get_serial_enabled,
5+
)
26

37

48
def test_settings_cache_alias(settings):
@@ -32,3 +36,17 @@ def test_get_serial_enabled(settings):
3236
] = "django.core.cache.backends.dummy.DummyCache"
3337
settings.UNICORN["CACHE_ALIAS"] = "unicorn_cache"
3438
assert get_serial_enabled() is False
39+
40+
41+
def test_settings_minify_html_false(settings):
42+
settings.UNICORN["MINIFY_HTML"] = False
43+
44+
assert get_minify_html_enabled() is False
45+
46+
47+
def test_settings_minify_html_true(settings):
48+
settings.UNICORN["MINIFY_HTML"] = True
49+
50+
assert get_minify_html_enabled() is True
51+
52+
settings.UNICORN["MINIFY_HTML"] = False

0 commit comments

Comments
 (0)