uvicorn

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Uvicorn Skill Guide

Uvicorn使用指南

Uvicorn is a lightning-fast ASGI server implementation, using uvloop and httptools. It's the go-to server for modern Python async web frameworks.
Uvicorn是一款基于uvloop和httptools实现的超快速ASGI服务器,是现代Python异步Web框架的首选服务器。

Quick Start

快速开始

Basic Usage

基础用法

bash
undefined
bash
undefined

Run ASGI app

Run ASGI app

uvicorn main:app
uvicorn main:app

With host/port

With host/port

uvicorn main:app --host 0.0.0.0 --port 8000
uvicorn main:app --host 0.0.0.0 --port 8000

Development with auto-reload

Development with auto-reload

uvicorn main:app --reload
undefined
uvicorn main:app --reload
undefined

Common Patterns

常见使用模式

1. Simple ASGI Application

1. 简单ASGI应用

python
undefined
python
undefined

main.py

main.py

async def app(scope, receive, send): assert scope['type'] == 'http'
await send({
    'type': 'http.response.start',
    'status': 200,
    'headers': [(b'content-type', b'text/plain')],
})
await send({
    'type': 'http.response.body',
    'body': b'Hello, World!',
})
undefined
async def app(scope, receive, send): assert scope['type'] == 'http'
await send({
    'type': 'http.response.start',
    'status': 200,
    'headers': [(b'content-type', b'text/plain')],
})
await send({
    'type': 'http.response.body',
    'body': b'Hello, World!',
})
undefined

2. FastAPI Application

2. FastAPI应用

python
undefined
python
undefined

main.py

main.py

from fastapi import FastAPI
app = FastAPI()
@app.get("/") async def root(): return {"message": "Hello World"}

```bash
uvicorn main:app --reload
from fastapi import FastAPI
app = FastAPI()
@app.get("/") async def root(): return {"message": "Hello World"}

```bash
uvicorn main:app --reload

3. Application Factory Pattern

3. 应用工厂模式

python
undefined
python
undefined

main.py

main.py

from fastapi import FastAPI
def create_app(): app = FastAPI() # Configure app return app
app = create_app()

```bash
uvicorn --factory main:create_app
from fastapi import FastAPI
def create_app(): app = FastAPI() # Configure app return app
app = create_app()

```bash
uvicorn --factory main:create_app

4. Programmatic Server Control

4. 程序化控制服务器

python
import uvicorn
python
import uvicorn

Simple run

Simple run

if name == "main": uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

```python
import asyncio
import uvicorn

async def main():
    config = uvicorn.Config("main:app", port=5000, log_level="info")
    server = uvicorn.Server(config)
    await server.serve()

if __name__ == "__main__":
    asyncio.run(main())
if name == "main": uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

```python
import asyncio
import uvicorn

async def main():
    config = uvicorn.Config("main:app", port=5000, log_level="info")
    server = uvicorn.Server(config)
    await server.serve()

if __name__ == "__main__":
    asyncio.run(main())

5. Configuration with Environment Variables

5. 环境变量配置

bash
export UVICORN_HOST="0.0.0.0"
export UVICORN_PORT="8000"
export UVICORN_RELOAD="true"
uvicorn main:app
bash
export UVICORN_HOST="0.0.0.0"
export UVICORN_PORT="8000"
export UVICORN_RELOAD="true"
uvicorn main:app

Production Deployment

生产环境部署

Multi-Process Workers

多进程工作者

bash
undefined
bash
undefined

Use multiple worker processes

Use multiple worker processes

uvicorn main:app --workers 4
uvicorn main:app --workers 4

Note: Can't use --reload with --workers

Note: Can't use --reload with --workers

undefined
undefined

Gunicorn + Uvicorn

Gunicorn + Uvicorn

bash
undefined
bash
undefined

Install gunicorn

Install gunicorn

pip install gunicorn
pip install gunicorn

Run with Gunicorn process manager

Run with Gunicorn process manager

gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker
undefined
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker
undefined

HTTPS/SSL

HTTPS/SSL

bash
uvicorn main:app --ssl-keyfile=./key.pem --ssl-certfile=./cert.pem
bash
uvicorn main:app --ssl-keyfile=./key.pem --ssl-certfile=./cert.pem

Unix Socket

Unix套接字

bash
uvicorn main:app --uds /tmp/uvicorn.sock
bash
uvicorn main:app --uds /tmp/uvicorn.sock

Configuration Options

配置选项

Common CLI Flags

常用CLI标志

bash
uvicorn main:app \
  --host 0.0.0.0 \
  --port 8000 \
  --reload \
  --reload-dir ./app \
  --log-level info \
  --access-log \
  --workers 4
bash
uvicorn main:app \
  --host 0.0.0.0 \
  --port 8000 \
  --reload \
  --reload-dir ./app \
  --log-level info \
  --access-log \
  --workers 4

Key Settings

关键设置

  • --host
    : Bind host (default: 127.0.0.1)
  • --port
    : Bind port (default: 8000)
  • --reload
    : Enable auto-reload for development
  • --workers
    : Number of worker processes
  • --log-level
    : Logging level (critical, error, warning, info, debug)
  • --access-log
    : Enable access logging
  • --factory
    : Treat app as application factory
  • --host
    : 绑定主机(默认:127.0.0.1)
  • --port
    : 绑定端口(默认:8000)
  • --reload
    : 启用开发模式自动重载
  • --workers
    : 工作进程数量
  • --log-level
    : 日志级别(critical、error、warning、info、debug)
  • --access-log
    : 启用访问日志
  • --factory
    : 将应用视为应用工厂

Docker Integration

Docker集成

Dockerfile

Dockerfile

dockerfile
FROM python:3.12-slim
WORKDIR /app
dockerfile
FROM python:3.12-slim
WORKDIR /app

Install dependencies

Install dependencies

COPY requirements.txt . RUN pip install -r requirements.txt
COPY requirements.txt . RUN pip install -r requirements.txt

Copy application

Copy application

COPY . .
COPY . .

Run with uvicorn

Run with uvicorn

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
undefined
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
undefined

Docker Compose with Hot Reload

带热重载的Docker Compose

yaml
services:
  app:
    build: .
    ports:
      - "8000:8000"
    environment:
      - UVICORN_RELOAD=true
    volumes:
      - .:/app
    command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload
yaml
services:
  app:
    build: .
    ports:
      - "8000:8000"
    environment:
      - UVICORN_RELOAD=true
    volumes:
      - .:/app
    command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload

Troubleshooting

故障排查

Common Issues

常见问题

  1. Port already in use: Change port or kill existing process
  2. Module not found: Check PYTHONPATH or use
    --app-dir
  3. Reload not working: Ensure watching correct directories with
    --reload-dir
  4. Worker count: Use
    --workers
    for production, avoid with
    --reload
  1. 端口已被占用:更换端口或终止现有进程
  2. 模块未找到:检查PYTHONPATH或使用
    --app-dir
  3. 重载不生效:确保使用
    --reload-dir
    监听正确的目录
  4. 工作进程数量:生产环境使用
    --workers
    ,避免与
    --reload
    同时使用

Debug Mode

调试模式

bash
uvicorn main:app --reload --log-level debug
bash
uvicorn main:app --reload --log-level debug

Health Checks

健康检查

python
@app.get("/health")
async def health():
    return {"status": "healthy"}
python
@app.get("/health")
async def health():
    return {"status": "healthy"}