Flask comes with built-in static file serving, but compression support is completely missing. I think the way whitenoise implements it and compress files during builds. The following should serve the compressed static files.
import os from flask import current_app, request, safe_join def send_compressed_file(filename, formats=[('br', 'br'), ('gzip', 'gz')]): if not current_app.has_static_folder: raise RuntimeError('No static folder for the current application') accept_encoding = request.headers.get('Accept-Encoding', None) if not accept_encoding: return current_app.send_static_file(filename) encodings = [encoding.trim() for encoding in accept_encoding.split(',')] for format, extension in formats: compressed = filename + extension if format in encodings and os.path.exists(safe_join(current_app.static_folder, compressed)): return current_app.send_static_file(compressed) return current_app.send_static_file(filename)
Than I would simply hook it into the
def production(): app.view_functions['static'] = send_compressed_file return app
Because it is very performance critical (every static file request hits this function) I would like to get some performance suggestions. Promblems that I encountered myself:
- I think
os.path.existsis not efficient? How could I store file paths better?