uvicorn 极简教程:Python 的 ASGI Web 服务器
Uvicorn 是一个基于 uvloop 和 httptools 构建的超快 ASGI 服务器,通常用于运行 FastAPI 或 Starlette 应用。官方文档:https://uvicorn.dev/
1. 安装
建议安装标准版(包含 Cython 依赖,速度更快):
pip install "uvicorn[standard]"
最小安装仅包含基础依赖:
pip install uvicorn
2. 编写最简单的应用
创建一个名为 main.py 的文件。
场景 A:配合 FastAPI(最常用)
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
场景 B:原生 ASGI 应用(不依赖框架)
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, Uvicorn!',})
3. 启动服务器 (命令行方式)
在终端中运行:
uvicorn main:app --reload


