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.