---
title: "如何用 uWSGI 托管 Django"
version: 6.1
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/6.1/howto/deployment/wsgi/uwsgi/
canonical: https://djangodocs.dev/zh-hans/6.1/howto/deployment/wsgi/uwsgi/
---
# 如何用 uWSGI 托管 Django

[uWSGI](https://uwsgi-docs.readthedocs.io/) 是一个快速的，自我驱动的，对开发者和系统管理员友好的应用容器服务器，完全由 C 编写。

> **See also**
>
> uWSGI 文档提供了一个覆盖 Django，nginx，和 uWSGI（一个配置，多种适配）的 [教程](https://uwsgi.readthedocs.io/en/latest/tutorials/Django_and_nginx.html) 。以下文档专注于如何用 uWSGI 集成 Django。

## 前置条件：uWSGI

uWSGI 百科介绍了几种 [安装流程](https://uwsgi-docs.readthedocs.io/en/latest/Install.html)。Pip （Python 包管理器）能让你仅用一行代码就安装任意版本的 uWSGI。例子：

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

### uWSGI 模块

uWSGI以 客户-服务器模式运行。你的网站服务器（如 nginx、Apache）与 `django-uwsgi` “worker” 进程进行通信，以提供动态内容。

### 配置并启动用于 Django 的 uWSGI 服务器

uWSGI 支持多种配置进程的方式。参考 uWSGI 的 [配置文档](https://uwsgi.readthedocs.io/en/latest/Configuration.html)。

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

```shell
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，这就是你运行 `django-admin startproject mysite` （使用你的项目名替换 `mysite`）后得到的目录结构。若该文件不存在，你需要创建它。参考文档 [如何使用 WSGI 进行部署](/zh-hans/6.1/howto/deployment/wsgi/) 看看你需要配置的默认内容，以及你还能添加什么。

Django 指定的参数如下：

- `chdir`：需要包含于 Python 的导入路径的目录的路径——例如，包含 `mysite` 包的目录。
- `module`：要使用的 WSGI 模块——可能是 [`startproject`](/zh-hans/6.1/ref/django-admin/#django-admin-startproject) 创建的 `mysite.wsgi` 的模块。
- `env`：至少要包括 [`DJANGO_SETTINGS_MODULE`](/zh-hans/6.1/topics/settings/#envvar-DJANGO_SETTINGS_MODULE)。
- `home`: 可选的路径，指向你工程的虚拟环境。

示例 INI 配置文件：

```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 配置文件的使用方法：

```shell
uwsgi --ini uwsgi.ini
```

> **为文件上传修复 UnicodeEncodeError**
>
> 如果在上传包含非 ASCII 字符的文件名的文件时出现 `UnicodeEncodeError`，请确保 uWSGI 配置允许接受非 ASCII 文件名，方法是将以下内容添加到你的 `uwsgi.ini` 文件中：
>
> ```ini
> env = LANG=en_US.UTF-8
> ```
>
> 参考 Unicode 参考指引的 [文件](/zh-hans/6.1/ref/unicode/#unicode-files) 章节获取细节信息。

参考 uWSGI 文档 [管理 uWSGI 进程](https://uwsgi-docs.readthedocs.io/en/latest/Management.html) 获取更多关于开启，关闭和重载 uWSGI workers 的信息。
