在 Django 中正确使用 wsgi.py

Using wsgi.py correctly in Django

当我部署我的 Django 站点时,我对 wsgi.py 文件以及它在本地使用与 Gunicorn 在生产中的使用方式有些困惑。

本地我有这个文件结构。

demo/
    __init__.py
    settings.py
    urls.py
    wsgi.py
manage.py

Settings.py 具有以下设置...WSGI_APPLICATION = 'demo.wsgi.application'

然而,一旦我在 Gunicorn 上部署了应用程序 运行,我收到一条错误消息,提示它找不到 wsgi.py 文件,为了使其正常工作,我必须再次创建该文件,例如这...

demo/
    __init__.py
    settings.py
    urls.py
    wsgi.py
manage.py
wsgi.py

这现在有效,但它向我暗示 Gunicorn 忽略了 Djangos 设置文件 demo/settings.py 中的 WSGI_APPLICATION 设置,对吗?如果是这样,Gunicorn 是从哪里获得自己对 wsgi.py 文件位置的引用以及本地有何不同?

这是我的 Gunicorn 设置,以防万一...

[program:gunicorn_process]
command=gunicorn wsgi:application -c /srv/test/gunicorn.conf.py
directory=/srv/test
user=root
autostart=true
autorestart=true
redirect_stderr=true

gunicorn.conf.py

bind = "127.0.0.1:8001"
workers = 3
worker_class = 'gevent'

你说得对,Gunicorn 忽略了 WSGI_APPLICATION 设置。此设置仅用于指定 runserver 命令使用的 wsgi 应用程序。

Gunicorn 对 Django 一无所知,但您可以指定 Gunicorn 应在哪个模块中查找应用程序。现在它在 wsgi 模块中寻找 application 属性:

command=gunicorn wsgi:application ...

要使用demo/中的文件,必须在Gunicorn命令中指定完整的模块路径:

command=gunicorn demo.wsgi:application ...