django/whitenoise storage backend causes an error

2019-04-15 00:37发布

问题:

i've encountered an 500 error when running my django app on heroku on debug off. after using rollbar to get idea why the error was happaning it reported the following:

ValueError: The file 'media/img 1.jpg' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f795706f550>.

i figured out it has to do with the STATICFILES_STORAGE setting, by removing it and using the default django STATICFILES_STORAGE ='django.contrib.staticfiles.storage.StaticFilesStorage' setting, it works. but any of these three none works and all causes the same error:

STATICFILES_STORAGE ='django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

in whitenoise troubleshooting it says to try to use django's manifestStaticFiles Storage and if the issue continues then the problem is in django and not whitenoise.

these are my production settings:

from django.conf import settings

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'rollbar.contrib.django.middleware.RollbarNotifierMiddleware',
)


DEBUG = False

# Email debugging configuration

ADMINS = (
    ('david', 'davidsidf@gmail.com'),
)

EMAIL_USE_TLS = True

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_HOST_USER = 'davidsidf@gmail.com'

EMAIL_HOST_PASSWORD = '*******'

EMAIL_PORT = 587


# Honor the 'X-Forwarded-Proto' header for request.is_secure()

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

ALLOWED_HOSTS = ['evening-garden-60868.herokuapp.com']

ROLLBAR = {
    'access_token': '*******************',
    'environment': 'development' if DEBUG else 'production',
    'branch': 'master',
    'root': '/absolute/path/to/code/root',
}

STATICFILES_DIRS = (
    os.path.join(BASE_DIR,"studio", "static"),
 )

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

回答1:

I think you are serving media file using static helper function like this:

urlpatterns = [
   ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

The media file fail to serve because static helper function you used in project/urls.py only works when DEBUG is on. There are security concerns if you serve user uploaded content this way in production.

You can of cause remove this restriction if you are really sure that your user's contents are safe.

def static(prefix, view=serve, **kwargs):
    ...
    # No-op if not in debug mode or an non-local prefix
    if not settings.DEBUG or (prefix and '://' in prefix):
        return []
    elif not prefix:
        raise ImproperlyConfigured("Empty static prefix not permitted")
    return [
        url(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs),
    ]