### Install WhiteNoise Source: https://github.com/evansd/whitenoise/blob/main/docs/index.md Install WhiteNoise using pip. This command is used for initial setup. ```sh pip install whitenoise ``` -------------------------------- ### QuickStart WSGI Application Integration Source: https://github.com/evansd/whitenoise/blob/main/docs/index.md Wrap your existing WSGI application with WhiteNoise and specify the root directory for static files. You can also add additional static files with a prefix. ```python from whitenoise import WhiteNoise from my_project import MyWSGIApp application = MyWSGIApp() application = WhiteNoise(application, root="/path/to/static/files") application.add_files("/path/to/more/static/files", prefix="more-files/") ``` -------------------------------- ### Example WHITENOISE_MIMETYPES Configuration Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Customize mimetypes for specific file extensions or filenames. WhiteNoise uses its own defaults and does not rely on system mimetypes. ```python WHITENOISE_MIMETYPES = { '.foo': 'application/x-foo', 'some-special-file': 'application/x-custom-type' } ``` -------------------------------- ### Set Environment Variable on Heroku Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Example command to set the DJANGO_STATIC_HOST environment variable for a Heroku application, pointing to the CloudFront distribution. ```bash heroku config:set DJANGO_STATIC_HOST=https://d4663kmspf1sqa.cloudfront.net ``` -------------------------------- ### Force Download PDFs with WhiteNoise Source: https://github.com/evansd/whitenoise/blob/main/docs/base.md Use the `add_headers_function` to modify response headers. This example forces PDF files to be downloaded by setting the `Content-Disposition` header. ```python def force_download_pdfs(headers, path, url): if path.endswith('.pdf'): headers['Content-Disposition'] = 'attachment' application = WhiteNoise(application, add_headers_function=force_download_pdfs) ``` -------------------------------- ### Custom Mimetypes Configuration Source: https://github.com/evansd/whitenoise/blob/main/docs/base.md Define custom mimetypes for specific files or extensions. This example shows how to map a custom file extension '.foo' to 'application/x-foo' and a specific filename 'some-special-file' to 'application/x-custom-type'. ```default {'.foo': 'application/x-foo'} {'some-special-file': 'application/x-custom-type'} ``` -------------------------------- ### Immutable File Detection with Regex Source: https://github.com/evansd/whitenoise/blob/main/docs/base.md Configure WhiteNoise to identify immutable files using a regular expression. This example matches URLs containing a 12-digit hexadecimal string before the file extension, suitable for versioned static assets. ```python import re def immutable_file_test(path, url): # Match filename with 12 hex digits before the extension # e.g. app.db8f2edc0c8a.js return re.match(r'^.+\.[0-9a-f]{12}\..+$', url) ``` -------------------------------- ### Enable WhiteNoise with Flask Factory Pattern Source: https://github.com/evansd/whitenoise/blob/main/docs/flask.md Integrate WhiteNoise when using the Flask factory pattern by wrapping the application object within the app creation function. This approach is suitable for more complex application setups. ```python from flask import Flask from sqlalchemy import create_engine from whitenoise import WhiteNoise from myapp import config from myapp.views import frontend def create_app(database_uri, debug=False): app = Flask(__name__) app.debug = debug # set up your database app.engine = create_engine(database_uri) # register your blueprints app.register_blueprint(frontend) # add whitenoise app.wsgi_app = WhiteNoise(app.wsgi_app, root="static/") # other setup tasks return app ``` -------------------------------- ### WhiteNoise Compression CLI Help Source: https://github.com/evansd/whitenoise/blob/main/docs/base.md Displays help information for the WhiteNoise compression command-line utility. Use this to understand available options for generating compressed files. ```console python -m whitenoise.compress --help ``` -------------------------------- ### Alternative WhiteNoise Storage Backend Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Use CompressedStaticFilesStorage if you need compression but do not require the caching behavior provided by ManifestStaticFilesStorage. ```python "whitenoise.storage.CompressedStaticFilesStorage" ``` -------------------------------- ### Configure Django Storage Backend Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md To troubleshoot WhiteNoise storage issues, temporarily switch to Django's default ManifestStaticFilesStorage. ```python STORAGES = { # ... "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ``` -------------------------------- ### WhiteNoise Class Initialization Source: https://github.com/evansd/whitenoise/blob/main/docs/base.md Initialize WhiteNoise by wrapping your existing WSGI application and specifying the root directory for static files. Additional configuration attributes can be passed as keyword arguments. ```APIDOC ## WhiteNoise Class ### Description Initializes the WhiteNoise middleware, wrapping an existing WSGI application to serve static files. ### Class Signature `WhiteNoise(application, root=None, prefix=None, **kwargs)` ### Parameters #### Positional Parameters - **application** (*callable*) - The original WSGI application to be wrapped. - **root** (*str*) - If set, this path is passed to the `add_files` method to serve files from this directory. - **prefix** (*str*) - If set, this prefix is passed to the `add_files` method for serving files under a specific URL path. #### Keyword Parameters - **`**kwargs`** - Additional keyword arguments are used to set configuration attributes for the WhiteNoise instance. Refer to the [configuration](#configuration) section for available attributes. ``` -------------------------------- ### Add Custom Static Folders with WhiteNoise Source: https://github.com/evansd/whitenoise/blob/main/docs/flask.md If your static files are not in the default 'static' folder, you can instantiate WhiteNoise without a root and then add your custom static folders using the add_files method. This allows for flexible static file management. ```python from flask import Flask from whitenoise import WhiteNoise app = Flask(__name__) app.wsgi_app = WhiteNoise(app.wsgi_app) my_static_folders = ( "static/folder/one/", "static/folder/two/", "static/folder/three/", ) for static in my_static_folders: app.wsgi_app.add_files(static) ``` -------------------------------- ### Configure Static Host via Environment Variable Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Avoid hardcoding the CDN URL by retrieving the DJANGO_STATIC_HOST from environment variables. This allows for flexible configuration without modifying settings.py. ```python import os STATIC_HOST = os.environ.get("DJANGO_STATIC_HOST", "") STATIC_URL = STATIC_HOST + "/static/" ``` -------------------------------- ### Configure Static Host with CloudFront Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Set the STATIC_HOST to your CloudFront distribution domain name when not in DEBUG mode. The STATIC_URL is then constructed by appending '/static/'. ```python STATIC_HOST = "https://d4663kmspf1sqa.cloudfront.net" if not DEBUG else "" STATIC_URL = STATIC_HOST + "/static/" ``` -------------------------------- ### Configure WhiteNoise StaticFilesStorage in Django Source: https://github.com/evansd/whitenoise/blob/main/docs/index.md Configure Django's STORAGES setting to use WhiteNoise's CompressedManifestStaticFilesStorage for compressed, cacheable static files. ```python STORAGES = { # ... "staticfiles": { "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage", }, } ``` -------------------------------- ### WhiteNoise.add_files Method Source: https://github.com/evansd/whitenoise/blob/main/docs/base.md Adds a directory of static files to be served by WhiteNoise. You can specify a URL prefix under which these files will be accessible. ```APIDOC ## WhiteNoise.add_files Method ### Description Adds a directory containing static files to be served by WhiteNoise. Files within this directory will be accessible under the specified URL prefix. ### Method Signature `add_files(root, prefix=None)` ### Parameters #### Positional Parameters - **root** (*str*) - The absolute path to the directory containing static files. #### Optional Parameters - **prefix** (*str*) - A URL prefix under which the files in the `root` directory will be served. WhiteNoise automatically appends a trailing slash if one is not provided. ``` -------------------------------- ### Configure Application Deployment with URL Prefix Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Set FORCE_SCRIPT_NAME and STATIC_URL to the correct prefix when deploying your Django app in a subdirectory. WhiteNoise automatically configures itself with these settings. ```python FORCE_SCRIPT_NAME = "/my-app" STATIC_URL = FORCE_SCRIPT_NAME + "/static/" ``` -------------------------------- ### Configure Django STATIC_ROOT Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Add this to your settings.py to define the root directory for static files. Ensure you run `./manage.py collectstatic` during deployment. ```python STATIC_ROOT = BASE_DIR / "staticfiles" ``` -------------------------------- ### Configure Static Files Directory with Webpack Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Add the build output directory to STATICFILES_DIRS to allow Django to find processed static files. Exclude build directories from version control. ```python STATICFILES_DIRS = [BASE_DIR / "static_build"] ``` -------------------------------- ### Set URL Prefix for Static Files with WhiteNoise Source: https://github.com/evansd/whitenoise/blob/main/docs/flask.md Configure WhiteNoise to serve static files from a specific URL prefix, such as 'assets/'. This changes the URL path for static files from the root to the specified prefix. ```python app.wsgi_app = WhiteNoise(app.wsgi_app, root="static/", prefix="assets/") ``` -------------------------------- ### Enable WhiteNoise with Flask Application Object Source: https://github.com/evansd/whitenoise/blob/main/docs/flask.md Wrap the Flask application object with WhiteNoise to serve static files from the default 'static/' folder. This is the simplest way to integrate WhiteNoise. ```python from flask import Flask from whitenoise import WhiteNoise app = Flask(__name__) app.wsgi_app = WhiteNoise(app.wsgi_app, root="static/") ``` -------------------------------- ### Find Missing Static Files Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Use this command to locate static files that Django cannot find. It shows all paths Django searches. ```sh python manage.py findstatic --verbosity 2 foo ``` -------------------------------- ### Run Django Collectstatic Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Before testing WhiteNoise with DEBUG disabled, run collectstatic to gather all static files. ```bash python manage.py collectstatic ``` -------------------------------- ### Use Django static template tag Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Prefer using the `static` template tag to reference static files instead of hardcoding URLs. This ensures correct path resolution. ```django {% load static %} Hi! ``` ```html Hi! ``` -------------------------------- ### Enable WhiteNoise in Django Development Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Add 'whitenoise.runserver_nostatic' to INSTALLED_APPS to allow WhiteNoise to handle static files during Django development with runserver. This ensures consistent behavior between development and production environments. ```python INSTALLED_APPS = [ # ... "whitenoise.runserver_nostatic", "django.contrib.staticfiles", # ... ] ``` -------------------------------- ### Define Immutable Files for Caching Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Configure WHITENOISE_IMMUTABLE_FILE_TEST to specify which static files are immutable and can be cached indefinitely. This can be a function returning a boolean or a regex string for URL matching. ```python import re def immutable_file_test(path, url): # Match filename with 12 hex digits before the extension # e.g. app.db8f2edc0c8a.js return re.match(r'^.+\.[0-9a-f]{12}\..+$', url) WHITENOISE_IMMUTABLE_FILE_TEST = immutable_file_test ``` -------------------------------- ### Add Custom Headers to Static Files Source: https://github.com/evansd/whitenoise/blob/main/docs/django.md Use WHITENOISE_ADD_HEADERS_FUNCTION to provide a function that modifies headers for each static file. The function receives headers, path, and URL, and should modify the headers dictionary in place. ```python def force_download_pdfs(headers, path, url): if path.endswith('.pdf'): headers['Content-Disposition'] = 'attachment' WHITENOISE_ADD_HEADERS_FUNCTION = force_download_pdfs ``` -------------------------------- ### Add WhiteNoise to Django MIDDLEWARE Source: https://github.com/evansd/whitenoise/blob/main/docs/index.md Add WhiteNoiseMiddleware to your Django project's MIDDLEWARE list in settings.py. It should be placed after SecurityMiddleware. ```python MIDDLEWARE = [ # ... "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", # ... ] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.