手動使用 ASGI 伺服器

ASGI(異步伺服器閘道介面)旨在為 Litestar 等異步 Python 網頁框架與異步網頁伺服器之間提供標準介面。

There are several popular ASGI servers available, and you can choose the one that best fits your application's needs.

使用時機

Running your application manually with an ASGI server is usually only ideal in development and testing environments.

It is generally recommended to run your production workloads inside a containerized environment, such as Docker or Kubernetes or via a process control system such as Supervisor or systemd.

Alternatives

For different deployment scenarios, consider these alternatives:

  • systemd

    A system and service manager, integrated into many Linux distributions for managing system processes.

    備註

    官方文件即將推出

  • Supervisor:

    A process control system that can be used to automatically start, stop and restart processes; includes a web UI.

  • Docker

    Ideal for containerized environments, offering isolation and scalability.

選擇 ASGI 伺服器

Uvicorn is an ASGI server that supports HTTP/1.1 and WebSocket.

Hypercorn is an ASGI server that was initially part of Quart, and supports HTTP/1.1, HTTP/2, and WebSocket.

Daphne is an ASGI server that was originally developed for Django Channels, and supports HTTP/1.1, HTTP/2, and WebSocket.

Granian is a Rust-based ASGI server that supports HTTP/1.1, HTTP/2, and WebSocket.

安裝 ASGI 伺服器

使用 pip 安裝 Uvicorn
pip install uvicorn
使用 pip 安裝 Hypercorn
pip install hypercorn
使用 pip 安裝 Daphne
pip install daphne
使用 pip 安裝 Granian
pip install granian

執行 ASGI 伺服器

Assuming your app is defined in the same manner as Minimal Example, you can run the ASGI server with the following command:

Run Uvicorn with the default configuration
uvicorn app:app
主控臺輸出
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Run Hypercorn with the default configuration
hypercorn app:app
主控臺輸出
[2023-11-12 23:31:26 -0800] [16748] [INFO] Running on http://127.0.0.1:8000 (CTRL + C to quit)
使用預設組態執行 Daphne
daphne app:app
主控臺輸出
INFO - 2023-11-12 23:31:51,571 - daphne.cli - cli - Starting server at tcp:port=8000:interface=127.0.0.1
INFO - 2023-11-12 23:31:51,572 - daphne.server - server - Listening on TCP address 127.0.0.1:8000
使用預設組態執行 Granian
granian --interface asgi app:app
主控臺輸出
[INFO] Starting granian
[INFO] Listening at: 127.0.0.1:8000

Gunicorn with Uvicorn workers

重要

Deprecation Notice

The Gunicorn+Uvicorn pattern is considered legacy for ASGI deployments since Uvicorn 0.30.0+ includes native worker management.

Uvicorn added a new multiprocess manager, that is meant to replace Gunicorn entirely. Refer to the pull request #2183 for implementation details.

For new deployments, use Uvicorn directly.