如何将Django与Uwsgi结合使用

uWSGI 是一个快速的、自我修复的、开发人员/系统管理员友好的应用程序容器服务器,用纯C编码。

参见

UWSGI文档提供 tutorial 包括django、nginx和uwsgi(一个可能的多个部署设置)。下面的文档主要介绍如何将Django与Uwsgi集成。

前提条件:UWSGI

Uwsgi wiki描述了几个 installation procedures . 使用python包管理器pip,您可以用一个命令安装任何uwsgi版本。例如:

# Install current stable version.
$ python -m pip install uwsgi

# Or install LTS (long term support).
$ python -m pip install https://projects.unbit.it/downloads/uwsgi-lts.tar.gz

UWSGI模型

UWSGI运行在客户端-服务器模型上。您的Web服务器(例如,nginx、apache)与 django-uwsgi “工作者”流程,提供动态内容。

为Django配置和启动Uwsgi服务器

UWSGI支持多种配置流程的方法。参见UWSGI configuration documentation .

以下是启动uWSGI服务器的示例命令:

uwsgi --chdir=/path/to/your/project \
    --module=mysite.wsgi:application \
    --env DJANGO_SETTINGS_MODULE=mysite.settings \
    --master --pidfile=/tmp/project-master.pid \
    --socket=127.0.0.1:49152 \      # can also be a file
    --processes=5 \                 # number of worker processes
    --uid=1000 --gid=2000 \         # if root, uwsgi can drop privileges
    --harakiri=20 \                 # respawn processes taking more than 20 seconds
    --max-requests=5000 \           # respawn processes after serving 5000 requests
    --vacuum \                      # clear environment on exit
    --home=/path/to/virtual/env \   # optional path to a virtual environment
    --daemonize=/var/log/uwsgi/yourproject.log      # background the process

这假定您有一个名为 mysite 以及其中的一个模块 mysite/wsgi.py 包含一个wsgi application 对象。这是你运行时的布局 django-admin startproject mysite (使用您自己的项目名称代替 mysite )最新版本的django。如果此文件不存在,则需要创建它。见 如何使用wsgi部署 关于您应该放在这个文件中的默认内容的文档,以及其他可以添加到其中的内容。

Django的具体选项如下:

  • chdir :需要位于python导入路径上的目录的路径,即包含 mysite 包。

  • module :要使用的wsgi模块--可能是 mysite.wsgi 模块,即 startproject 创造。

  • env :应该至少包含 DJANGO_SETTINGS_MODULE .

  • home :项目虚拟环境的可选路径。

Ini配置文件示例:

[uwsgi]
chdir=/path/to/your/project
module=mysite.wsgi:application
master=True
pidfile=/tmp/project-master.pid
vacuum=True
max-requests=5000
daemonize=/var/log/uwsgi/yourproject.log

Ini配置文件用法示例:

uwsgi --ini uwsgi.ini

定影 UnicodeEncodeError 用于文件上载

如果你得到了一个 UnicodeEncodeError 上载文件名包含非ASCII字符的文件时,请确保将uWSGI配置为接受非ASCII文件名,方法是将以下内容添加到 uwsgi.ini

env = LANG=en_US.UTF-8

文件夹 有关详细信息,请参阅Unicode参考指南的部分。

查看UWSGI文档 managing the uWSGI process 有关启动、停止和重新加载UWSGI工人的信息。