zenwalker
9/7/2014 - 10:35 PM

Compress HTML to one line in Django (python3)

Compress HTML to one line in Django (python3)

import re


class CompressHtmlMiddleware(object):

    def __init__(self):
        self.whitespace = re.compile(r'^\s+', re.MULTILINE)
        self.linebreak = re.compile(r'\n', re.MULTILINE)

    def process_response(self, request, response):
        if "Content-Type" in response:
            if "text" in response['Content-Type']:
                response.content = self.whitespace.sub('', response.content.decode())
                response.content = self.linebreak.sub('', response.content.decode())
        return response