DeveloperBreeze

Htmlmin Development Tutorials, Guides & Insights

Unlock 1+ expert-curated htmlmin tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your htmlmin skills on DeveloperBreeze.

Optimizing HTML Delivery in Flask with Minification and Compression

Tutorial August 20, 2024
python

from flask import Response
import gzip
from io import BytesIO

@app.after_request
def after_request(response):
    if response.content_type == 'text/html; charset=utf-8':
        minified = minify(response.get_data(as_text=True))
        gzip_buffer = BytesIO()
        with gzip.GzipFile(mode='wb', fileobj=gzip_buffer) as gzip_file:
            gzip_file.write(minified.encode('utf-8'))

        response.set_data(gzip_buffer.getvalue())
        response.headers['Content-Encoding'] = 'gzip'
        response.headers['Content-Length'] = len(response.get_data())
    return response
  • gzip.GzipFile: Compresses the minified HTML content.
  • response.headers['Content-Encoding'] = 'gzip': Informs the browser that the content is compressed using gzip.
  • response.headers['Content-Length']: Updates the Content-Length header to reflect the compressed size.