django-compression-middleware

raw JSON →
0.5.0 verified Fri May 01 auth: no python

Django middleware to compress HTTP responses using Brotli, Zstd, Gzip, or Deflate, with automatic content negotiation. Provides both WSGI and ASGI support. Current version 0.5.0, released sporadically.

pip install django-compression-middleware
error ImportError: cannot import name 'CompressionMiddleware' from 'compression_middleware.middleware'
cause In version 0.5.0, the module path changed. The old import 'compression_middleware.middleware' is gone.
fix
Change import to 'from compression_middleware import CompressionMiddleware'.
error AttributeError: 'CompressionMiddleware' object has no attribute 'process_response'
cause The middleware is implemented differently (uses __call__ for ASGI/WSGI compat). Trying to override process_response will not work.
fix
Do not subclass or override process_response. Instead, use the middleware as-is.
error TypeError: __init__() got an unexpected keyword argument 'get_response'
cause Using the middleware class directly in MIDDLEWARE setting without parentheses (old-style) but the class expects no arguments.
fix
Use the dotted string path: 'compression_middleware.CompressionMiddleware' (not an instance).
breaking Place middleware after SecurityMiddleware but before SessionMiddleware and CommonMiddleware. Incorrect order can break compression or security headers.
fix Ensure order: SecurityMiddleware, CompressionMiddleware, then others.
gotcha The library does NOT compress responses smaller than COMPRESSION_MIN_LENGTH. Default is 150 bytes. If you expect small responses to be compressed, reduce this value.
fix Set COMPRESSION_MIN_LENGTH = 0 in settings to compress all responses.
gotcha Only responses with a status code in the 200-399 range are compressed. 404, 500, etc., are skipped.
fix Override by subclassing or adjusting middleware logic if needed.
deprecated In version 0.5.0, the import path from 'compression_middleware.middleware' was removed. Must import directly from 'compression_middleware'.
fix Use 'from compression_middleware import CompressionMiddleware'.

Add CompressionMiddleware to MIDDLEWARE list. Place it after SecurityMiddleware but before other middleware for best performance. Optionally set COMPRESSION_ALGORITHMS and COMPRESSION_MIN_LENGTH in settings.

# settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'compression_middleware.CompressionMiddleware',
    # ... other middleware
]

# Optional: configure compression algorithms
COMPRESSION_ALGORITHMS = ['br', 'zstd', 'gzip', 'deflate']
COMPRESSION_MIN_LENGTH = 150  # bytes; default is 150