uvicorn
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUvicorn 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
undefinedbash
undefinedRun 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
undefineduvicorn main:app --reload
undefinedCommon Patterns
常见使用模式
1. Simple ASGI Application
1. 简单ASGI应用
python
undefinedpython
undefinedmain.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!',
})undefinedasync 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!',
})undefined2. FastAPI Application
2. FastAPI应用
python
undefinedpython
undefinedmain.py
main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
```bash
uvicorn main:app --reloadfrom fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
```bash
uvicorn main:app --reload3. Application Factory Pattern
3. 应用工厂模式
python
undefinedpython
undefinedmain.py
main.py
from fastapi import FastAPI
def create_app():
app = FastAPI()
# Configure app
return app
app = create_app()
```bash
uvicorn --factory main:create_appfrom fastapi import FastAPI
def create_app():
app = FastAPI()
# Configure app
return app
app = create_app()
```bash
uvicorn --factory main:create_app4. Programmatic Server Control
4. 程序化控制服务器
python
import uvicornpython
import uvicornSimple 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:appbash
export UVICORN_HOST="0.0.0.0"
export UVICORN_PORT="8000"
export UVICORN_RELOAD="true"
uvicorn main:appProduction Deployment
生产环境部署
Multi-Process Workers
多进程工作者
bash
undefinedbash
undefinedUse 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
undefinedundefinedGunicorn + Uvicorn
Gunicorn + Uvicorn
bash
undefinedbash
undefinedInstall 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
undefinedgunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker
undefinedHTTPS/SSL
HTTPS/SSL
bash
uvicorn main:app --ssl-keyfile=./key.pem --ssl-certfile=./cert.pembash
uvicorn main:app --ssl-keyfile=./key.pem --ssl-certfile=./cert.pemUnix Socket
Unix套接字
bash
uvicorn main:app --uds /tmp/uvicorn.sockbash
uvicorn main:app --uds /tmp/uvicorn.sockConfiguration 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 4bash
uvicorn main:app \
--host 0.0.0.0 \
--port 8000 \
--reload \
--reload-dir ./app \
--log-level info \
--access-log \
--workers 4Key Settings
关键设置
- : Bind host (default: 127.0.0.1)
--host - : Bind port (default: 8000)
--port - : Enable auto-reload for development
--reload - : Number of worker processes
--workers - : Logging level (critical, error, warning, info, debug)
--log-level - : Enable access logging
--access-log - : Treat app as application factory
--factory
- : 绑定主机(默认:127.0.0.1)
--host - : 绑定端口(默认:8000)
--port - : 启用开发模式自动重载
--reload - : 工作进程数量
--workers - : 日志级别(critical、error、warning、info、debug)
--log-level - : 启用访问日志
--access-log - : 将应用视为应用工厂
--factory
Docker Integration
Docker集成
Dockerfile
Dockerfile
dockerfile
FROM python:3.12-slim
WORKDIR /appdockerfile
FROM python:3.12-slim
WORKDIR /appInstall 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"]
undefinedCMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
undefinedDocker 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 --reloadyaml
services:
app:
build: .
ports:
- "8000:8000"
environment:
- UVICORN_RELOAD=true
volumes:
- .:/app
command: uvicorn main:app --host 0.0.0.0 --port 8000 --reloadTroubleshooting
故障排查
Common Issues
常见问题
- Port already in use: Change port or kill existing process
- Module not found: Check PYTHONPATH or use
--app-dir - Reload not working: Ensure watching correct directories with
--reload-dir - Worker count: Use for production, avoid with
--workers--reload
- 端口已被占用:更换端口或终止现有进程
- 模块未找到:检查PYTHONPATH或使用
--app-dir - 重载不生效:确保使用监听正确的目录
--reload-dir - 工作进程数量:生产环境使用,避免与
--workers同时使用--reload
Debug Mode
调试模式
bash
uvicorn main:app --reload --log-level debugbash
uvicorn main:app --reload --log-level debugHealth Checks
健康检查
python
@app.get("/health")
async def health():
return {"status": "healthy"}python
@app.get("/health")
async def health():
return {"status": "healthy"}