WhiteNoise

6.12.0 · active · verified Thu Apr 09

Radically simplified static file serving for WSGI applications. WhiteNoise takes a WSGI application and wraps it, serving static files directly from the application itself. It's commonly used with Django to serve `STATIC_ROOT` contents. Current version 6.12.0, with regular updates typically following major Django releases or when significant improvements are made.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to wrap a generic WSGI application with WhiteNoise to serve static files from a specified directory (`STATIC_ROOT`). The resulting `application` object can then be served by any WSGI server. Comments highlight optional but recommended production settings like compression and aggressive caching (`max_age`).

import os
from whitenoise import WhiteNoise

# Your existing WSGI application (e.g., from Django, Flask, or a simple function)
# For this example, we use a minimal dummy app:
def my_wsgi_app(environ, start_response):
    status = '200 OK'
    headers = [('Content-type', 'text/plain')]
    start_response(status, headers)
    return [b"Hello from the main WSGI app!"]

# Path to your static files (e.g., collected via Django's collectstatic)
# Ensure this directory exists and contains your static assets (e.g., 'staticfiles/hello.txt')
STATIC_ROOT = os.path.join(os.path.dirname(__file__), 'staticfiles')

# Wrap your WSGI application with WhiteNoise
# Basic setup: serves files from STATIC_ROOT at the root URL path ('/')
application = WhiteNoise(my_wsgi_app, root=STATIC_ROOT,
                         # For production, consider enabling compression and setting a max_age:
                         # gzip=True, brotli=True, # Requires 'zopfli' and 'brotli' packages
                         # max_age=31536000 # Cache static files for 1 year in browsers
                        )

# If you need to serve additional static directories or with specific URL prefixes:
# application.add_files('/path/to/another/static/dir', prefix='another-prefix/')

# The 'application' object is now ready to be served by any WSGI server
# e.g., gunicorn -w 4 your_project.wsgi:application

view raw JSON →