---
title: "如何使用 ASGI 来部署"
version: 3.0
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/3.0/howto/deployment/asgi/
canonical: https://djangodocs.dev/zh-hans/3.0/howto/deployment/asgi/
---
# 如何使用 ASGI 来部署

同 WSGI 一样，Django 也支持使用 [ASGI](https://asgi.readthedocs.io/en/latest/) 来部署，它是为了支持异步网络服务器和应用而新出现的 Python 标准。

Django's [`startproject`](/zh-hans/3.0/ref/django-admin/#django-admin-startproject) management command sets up a default ASGI
configuration for you, which you can tweak as needed for your project, and
direct any ASGI-compliant application server to use.

Django includes getting-started documentation for the following ASGI servers:

- [How to use Django with Daphne](/zh-hans/3.0/howto/deployment/asgi/daphne/)
- [How to use Django with Uvicorn](/zh-hans/3.0/howto/deployment/asgi/uvicorn/)

## `application` 对象

Like WSGI, ASGI has you supply an `application` callable which
the application server uses to communicate with your code. It's commonly
provided as an object named `application` in a Python module accessible to
the server.

The [`startproject`](/zh-hans/3.0/ref/django-admin/#django-admin-startproject) command creates a file
`<project_name>/asgi.py` that contains such an `application` callable.

It's not used by the development server (`runserver`), but can be used by
any ASGI server either in development or in production.

ASGI servers usually take the path to the application callable as a string;
for most Django projects, this will look like `myproject.asgi:application`.

> **Warning**
>
> While Django's default ASGI handler will run all your code in a synchronous
> thread, if you choose to run your own async handler you must be aware of
> async-safety.
>
> Do not call blocking synchronous functions or libraries in any async code.
> Django prevents you from doing this with the parts of Django that are not
> async-safe, but the same may not be true of third-party apps or Python
> libraries.

## 配置 settings 模块

When the ASGI server loads your application, Django needs to import the
settings module — that's where your entire application is defined.

Django 利用 [`DJANGO_SETTINGS_MODULE`](/zh-hans/3.0/topics/settings/#envvar-DJANGO_SETTINGS_MODULE) 环境变量来定位合适的配置模块。它必须包含到配置模块的点式路径。开发环境和生产环境可以配置不同值；这都取决于你是如何组织配置的。

If this variable isn't set, the default `asgi.py` sets it to
`mysite.settings`, where `mysite` is the name of your project.

## Applying ASGI middleware

To apply ASGI middleware, or to embed Django in another ASGI application, you
can wrap Django's `application` object in the `asgi.py` file. For example:

```
from some_asgi_library import AmazingMiddleware
application = AmazingMiddleware(application)
```
