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