Using only gunicorn, django, and whitenoise how do I serve media?

…衆ロ難τιáo~ 提交于 2021-01-28 11:11:51

问题


I have my website finally working properly, but media files aren't served when debug = False what should I do? I've went through hell trying to make it work with nginx following this tutorial but it kept breaking and not serving static among other things, so I went with pure gunicorn and whitenoise. I really am not an expert at deploying, only development. Please help. Security isn't a problem with media files because only the admin can upload them, not end-users. Specifically I need to know if it's the end of the world leaving debug = True just for media files. Or if there's an easy way to serve them with debug = False.


回答1:


Here's how I've setup Whitenoise to serve static files for my application. I am using RedHat 7, but things should be similar in Ubuntu. My Django version is 1.11.

Note that it is NOT safe to run with DEBUG=True outside of your development environment.

First, I setup an environment variable pointing to the location of the static files:

export DJANGO_STATIC_ROOT=/home/<user>/<project>/staticfiles

In settings.py:

## Static files

STATIC_URL = '/static/'

if DEBUG:
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
else:
    STATIC_ROOT = environ['DJANGO_STATIC_ROOT']

## Whitenoise - Insert in 2nd place after SecurityMiddleware

MIDDLEWARE_CLASSES.insert(1,'whitenoise.middleware.WhiteNoiseMiddleware')

# Add app before django.contrib.staticfiles to enable Whitenoise in development

for i, app in enumerate(INSTALLED_APPS):
    if app == 'django.contrib.staticfiles':
        insert_point = i
INSTALLED_APPS.insert(insert_point,'whitenoise.runserver_nostatic')

Each time you deploy the app, be sure to run the collectstatic command to update the files in your DJANGO_STATIC_ROOT location:

./manage.py collectstatic

Best of luck!




回答2:


You shouldn’t use DEBUG=True in production, but if you are trying to test Whitenoise in development and get your medias served as well, this is the solution I came up with:

Replace in urls.py, this bit:

if settings.DEBUG:
    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

with:

if settings.DEBUG or settings.STAGE == 'local':
    urlpatterns.extend(
        [re_path(r'^%s(?P<path>.*)$' % re.escape(settings.MEDIA_URL.lstrip('/')), serve, kwargs={'document_root': settings.MEDIA_ROOT})]
    )

the critical part is to have a STAGE variable to indicate in which environment are you running the site.



来源:https://stackoverflow.com/questions/58630053/using-only-gunicorn-django-and-whitenoise-how-do-i-serve-media

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!