以 Webman 为参照,讲清楚 FastAPI 请求链路里各个组件的分工。
介绍FastAPI的重要组件
提示
CPython = Python 最常见的解释器实现,负责执行 Python 代码和对象内存管理
Uvicorn = ASGI Server,负责监听端口、处理 HTTP / WebSocket,并运行 ASGI Application
ASGI = Server 和 Python Web Application 之间的接口标准
Starlette = FastAPI 底层使用的 ASGI Web Framework / Toolkit
Pydantic = 数据模型、数据校验、类型转换、序列化
FastAPI = 基于 Starlette、使用 Pydantic,并增加依赖注入、OpenAPI 等能力的 API 框架
Typer = 与 FastAPI 设计思想相近的 CLI 框架,不参与 HTTP 请求
webman和 Fastapi 运行结构对比图
| Python / FastAPI 世界 | PHP / Webman 世界 | 主要职责 |
|---|---|---|
| Python Runtime / CPython | PHP Runtime / Zend Engine | 执行代码、对象生命周期、GC、内存管理 |
| Uvicorn | Workerman 的 HTTP Server / Event Loop 部分 | 网络、HTTP、WebSocket、事件循环 |
| Uvicorn Workers / Gunicorn | Workerman Master / Worker 管理部分 | 多进程、Worker 生命周期 |
| ASGI | 没有严格一一对应 | Server ↔ Application 的接口规范 |
| FastAPI | Webman | Web / API 框架 |
| Starlette | Webman 底层的 Route / Middleware / Request / Response 等能力 | Web 基础能力 |
| Pydantic | Validator + DTO + 类型转换 + Serializer | 数据模型和校验 |
| Typer | webman/console / Symfony Console | CLI 命令行能力 |
这是角色类比,不是完全同构。
尤其需要注意:
Workerman 同时承担了 Uvicorn 和一部分 Gunicorn 的职责。
Workerman
│
├── HTTP / 网络 / Event Loop
│ ≈ Uvicorn 的一部分职责
│
└── Master / Worker 管理
≈ Gunicorn / Uvicorn Workers 的一部分职责一个 FastAPI 请求大概经历什么
浏览器 / APP
│
│ HTTP / WebSocket
▼
┌───────────┐
│ Uvicorn │ 真正跑服务、监听端口的 ASGI Server
└───────────┘
│
│ ASGI
▼
┌─────────────────────┐
│ ASGI Middleware │ 作用在 ASGI 层的公共处理层
│ CORS / GZip / Auth │ CORS 跨域 / GZip 压缩 / Auth 鉴权
└─────────────────────┘
│
▼
┌───────────┐
│ FastAPI │ 组织 Web 能力和数据能力的 API 框架
└───────────┘
│
├──────────────────────┐
▼ ▼
┌────────────┐ ┌────────────┐
│ Starlette │ │ Pydantic │
└────────────┘ └────────────┘
│ │
Web / HTTP 数据处理
│ │
Route Model
Request Validation
Response Type Conversion
Middleware Serialization
WebSocket JSON Schema
│ │
└──────────┬───────────┘
▼
业务代码Uvicorn:真正负责跑服务的那一层
例如:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def index():
return {"hello": "world"}
启动:
uvicorn main:appASGI:异步服务器网关接口
- ASGI 是 Python Web Server 和 Python Web Application 之间的一套公共接口标准。
Uvicorn ←── ASGI ──→ FastAPI
或者:
Uvicorn ←── ASGI ──→ Starlette
ASGI 本身不是一个具体的软件,也不是 Web 框架。
规定了:Server 应该怎么调用 Application,
Application 又应该怎么接收请求事件、返回响应事件。HTTP 管外面,ASGI 管里面。
HTTP 负责:客户端 ↔ Server
ASGI 负责:Server ↔ Python Application
Starlette:Web 基础能力层
- 建立在 ASGI 之上的 Web 基础工具箱。
1.使用ASGI
- 可以运行,需要自己处理 http.response.start、http.response.body、Header、Body、状态码
async def app(scope, receive, send):
if scope["type"] != "http":
return
await send({
"type": "http.response.start",
"status": 200,
"headers": [
[b"content-type", b"application/json"]
]
})
await send({
"type": "http.response.body",
"body": b'{"message":"hello"}'
})2.使用 Starlette:
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
async def hello(request):
return JSONResponse({
"message": "hello"
})
app = Starlette(
routes=[
Route("/hello", hello)
]
)3.使用 FastAPI
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
async def hello():
return {
"message": "hello"
}重要
ASGI 解决“怎么通信”
Starlette 解决“怎么方便地开发 Web”
FastAPI 解决“怎么方便地开发现代 API”
Pydantic:数据层
- Pydantic是解决:数据长什么样、什么类型、是否合法、要不要转换、怎么序列化。
例如:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class UserCreate(BaseModel):
name: str
age: int
@app.post("/users")
async def create_user(user: UserCreate):
return user
发送:{"name": "Tom", "age": 18}- JSON → 解析 → 类型检查 → 校验 → 类型转换 → UserCreate → user.name / user.age
- 传非法数据(如 "age": "abc")会自动返回 422,业务代码不会执行。
Typer:CLI 命令行框架
- Python CLI 命令行框架。
import typer
app = typer.Typer()
@app.command()
def hello(
name: str,
age: int = 18
):
print(f"Hello {name}, age={age}")
if __name__ == "__main__":
app()
python main.py hello Tom --age 20Typer 不参与 FastAPI 的 HTTP 请求处理,它是和 FastAPI 设计思想相似的 CLI 框架,不是 FastAPI 的一部分。
版权所有
版权归属:念宇
