How to make Django serve static files with Gunicorn?

前端 未结 6 1233
小鲜肉
小鲜肉 2020-11-30 20:27

I want to run my django project under gunicorn on localhost. I installed and integrated gunicorn. When I run:

python manage.py run_gunicorn

6条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 21:16

    Whitenoise

    Post v4.0

    http://whitenoise.evans.io/en/stable/changelog.html#v4-0

    The WSGI integration option for Django (which involved editing wsgi.py) has been removed. Instead, you should add WhiteNoise to your middleware list in settings.py and remove any reference to WhiteNoise from wsgi.py. See the documentation for more details. (The pure WSGI integration is still available for non-Django apps.)

    Pre v4.0

    Heroku recommends this method at: https://devcenter.heroku.com/articles/django-assets:

    Your application will now serve static assets directly from Gunicorn in production. This will be perfectly adequate for most applications, but top-tier applications may want to explore using a CDN with Django-Storages.

    Install with:

    pip install whitenoise
    pip freeze > requirements.txt
    

    wsgi.py:

    import os
    from django.core.wsgi import get_wsgi_application
    from whitenoise.django import DjangoWhiteNoise
    
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "free_books.settings")
    application = get_wsgi_application()
    application = DjangoWhiteNoise(application)
    

    Tested on Django 1.9.

提交回复
热议问题