blog
blog copied to clipboard
简单使用 Gunicorn 托管 Django
一、把 Django 当作普通 WSGI 应用在 Gunicorn 中运行
参考:https://docs.djangoproject.com/zh-hans/2.2/howto/deployment/wsgi/gunicorn/
https://docs.gunicorn.org/en/latest/run.html#django
安装 Gunicorn 之后,可以使用 gunicorn
命令启动 Gunicorn 服务进程。最简模式下,只需要把包含了 WSGI 应用对象的 application 模块位置告诉 gunicorn,就可以启动了。因此对于典型的 Django 项目,像这样来调用 gunicorn:
# 在 manage.py 文件所在的目录(项目根目录)中运行命令:
$ gunicorn myproject.wsgi
这样会创建一个进程,包含了一个监听在 127.0.0.1:8000
的线程。
开发时提供静态文件服务
参考:https://docs.djangoproject.com/zh-hans/2.2/howto/static-files/#serving-static-files-during-development
使用以上命令启动 Gunicorn 并不能加载 CSS 等静态文件,需要执行以下操作才能加载静态文件(注意:这不适合生产环境,生产环境请使用 Nginx 等代理服务器提供静态文件服务):
例如,若 STATIC_URL
为 /static/
,你能通过添加以下代码片段至 urls.py 完成目的:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
二、Gunicorn 常用参数
参考:https://docs.gunicorn.org/en/latest/run.html#commonly-used-arguments
实例:绑定 IP 地址:
$ gunicorn --bind 192.168.x.xx:8000 myproject.wsgi