如何为我的 Django 项目的本地开发禁用白噪声?

How do I disable whitenoise for local development of my Django project?

我已经使用 Heroku Django project template. Heroku's template uses whitenoise 设置了一个部署在 Heroku 上的 Django 项目,以在我的项目根目录下的 /static/ 目录中收集静态文件。

这非常适合我的生产环境;每次我将新文件推送到我的服务器时,Heroku 运行s "manage.py collectstatic"。然而,在本地开发时很痛苦:每次我更改我的静态文件(例如,css),我必须手动 运行 "python manage.py collectstatic" 才能在我的开发服务器上看到更改。

有没有一种简单的方法可以在我的本地机器上禁用白噪声,这样我就不必每次都运行"python manage.py collectstatic"查看本地静态文件的更改?

我已经尝试创建一个单独的 "development_settings.py" 文件并删除该文件中对 whitenoise 的所有引用,但它不起作用,因为 wsgi.py 中仍然引用了 whitenoise,这会导致错误。

虽然我没有找到在我的开发服务器上禁用白噪声的简单方法,但我确实找到了一个方便的解决方法来简化整个过程:

向您的 .bash_profile 文件(或 bin/activate 如果您正在使用虚拟环境进行开发)添加一个新的命令别名,同时运行 collectstatic 和启动服务器:

alias launch='python manage.py collectstatic --noinput; foreman start'

默认的 Heroku 模板似乎指定了旧版本的 WhiteNoise。如果你运行

pip install --upgrade whitenoise

您应该会发现它会在开发过程中自动获取对静态文件的更改(即当 settings.DEBUGTrue 时)。

当前版本的 whitenoise 会自动获取静态文件中的更改。但它会大大减慢 runserver 的启动速度,因为它会遍历所有静态文件。我通过在 runserver 中禁用 whitenoise 来解决这个问题。现在我的 wsgi.py 看起来像这样:

import os
import sys

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "...")

application = get_wsgi_application()

# guess whether this is a runserver invocation with staticfiles
has_staticfiles = False
if 'runserver' in sys.argv:
    from django.conf import settings
    import inspect
    if settings.DEBUG:
        has_staticfiles = any(
            "django/contrib/staticfiles/management/commands/runserver"
            in x[1]
            for x in inspect.stack())

if has_staticfiles:
    print('runserver with staticfiles detected, skipping whitenoise')
else:
    # Do not use whitenoise with runserver, as it's slow
    from whitenoise.django import DjangoWhiteNoise
    application = DjangoWhiteNoise(application)

WhiteNoise 有一个名为 WHITENOISE_AUTOREFRESH 的设置正是出于这个原因。

来自WhiteNoise Docs

WHITENOISE_AUTOREFRESH: Rechecks the filesystem to see if any files have changed before responding. This is designed to be used in development where it can be convenient to pick up changes to static files without restarting the server. For both performance and security reasons, this setting should not be used in production.

这个的默认设置是 settings.DEBUG 的值,所以如果你是 运行 开发服务器,它应该默认打开。