DeveloperBreeze

Web Optimization. Development Tutorials, Guides & Insights

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

Optimizing HTML Delivery in Flask with Minification and Compression

Tutorial August 20, 2024
python

Purpose: Compress the HTML response to reduce its size and improve load times.

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