Flask-Compress is a Flask extension that allows you to easily compress your Flask application's responses using various algorithms like gzip, deflate, brotli, or zstandard. It helps reduce bandwidth usage and improve page load times. The library is actively maintained, with the current version being 1.24, and it typically sees releases for bug fixes, performance improvements, and feature enhancements.
pip install flask-compressVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to initialize Flask-Compress with your Flask application. Once initialized, Flask-Compress automatically compresses responses for specified MIME types, such as HTML or JSON, without further configuration. The `/large-data` endpoint serves a large JSON payload which will be compressed.
For static files, consider configuring your front-end web server (e.g., Nginx, Apache) to pre-compress or dynamically compress them, rather than relying on Flask-Compress.
To enable ETag for streaming, set `COMPRESS_EVALUATE_CONDITIONAL_REQUEST` to `True` and optionally `COMPRESS_STREAMING_ENDPOINT_CONDITIONAL` for specific endpoints. Evaluate memory usage carefully.
Monitor server CPU usage after enabling compression. Adjust `COMPRESS_LEVEL` (for gzip/deflate) or `COMPRESS_BROTLI_QUALITY` to find an optimal balance between compression ratio and CPU load. If CPU becomes a bottleneck, offload compression to a reverse proxy or CDN.
Install the package using pip: `pip install flask-compress`
Ensure you instantiate the 'Compress' object before calling 'init_app' and pass the Flask application instance:
```python
from flask import Flask
from flask_compress import Compress
compress = Compress()
def create_app():
app = Flask(__name__)
compress.init_app(app)
return app
# Or, if 'app' is immediately available:
# app = Flask(__name__)
# Compress(app)
```Install the 'brotli' package using pip: `pip install brotli`