From 25e6aa95316759d6409543609652928c1c28fc73 Mon Sep 17 00:00:00 2001 From: Mina Gaid Date: Wed, 16 Jan 2019 22:34:13 +0000 Subject: [PATCH] Update middleware.py --- htmlmin/middleware.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/htmlmin/middleware.py b/htmlmin/middleware.py index 00eeaee5..4395d5fa 100644 --- a/htmlmin/middleware.py +++ b/htmlmin/middleware.py @@ -27,15 +27,23 @@ def process_request(self, request): class HtmlMinifyMiddleware(object): - def __init__(self, get_response = None): + def __init__(self, get_response): self.get_response = get_response - - + def __call__(self, request): response = self.get_response(request) - - self.process_response(request, response) - + + if 'text/html' in response.get('Content-Type', ''): + try: + match = re.search(r'charset=([^;\s]+)', response['Content-Type']) + encoding = match.group(1) if match else 'utf-8' + response.content = str(htmlmin.minify(response.content.decode(encoding)), + remove_comments=True, + remove_empty_space=True, + pre_tags=(u'pre', u'code', u'textarea')) + except Exception as e: + logger(e) + return response def can_minify_response(self, request, response):