FastAPI 是一个现代化的高性能 Python Web 框架,专为构建 API(应用程序编程接口) 而设计。它以简洁的语法、强大的类型系统、异步支持及自动化文档生成能力著称,适用于开发高效、可扩展且易于维护的 Web 服务。以下从多个维度详细解析其定义:
高性能
基于 ASGI(Asynchronous Server Gateway Interface) 规范,使用轻量级的异步框架 Starlette 处理底层网络通信,结合数据模型库 Pydantic 实现高效的数据验证与序列化。其性能与 Node.js 和 Go 框架相当,支持每秒处理数万请求。
async/await
语法支持异步操作,适用于高并发场景(如实时通信、高频 API 调用)。开发效率
生产就绪
分层架构
Request -> [ASGI Server (Uvicorn/Daphne)]
-> [FastAPI App]
-> [路由系统 (APIRouter)]
-> [依赖注入 (Dependencies)]
-> [端点函数 (Endpoint)]
-> [响应模型 (Pydantic)]
-> [自动文档生成]
APIRouter
模块化组织 API 端点,支持路径参数、查询参数、请求体等多类型输入。数据流模型
# 请求处理流程
1. 请求接收 -> 2. 路由匹配 -> 3. 依赖解析
-> 4. 参数验证(Pydantic) -> 5. 业务逻辑执行
-> 6. 响应序列化 -> 7. 文档更新
asyncpg
、aiomysql
)处理高并发数据请求。特性 | FastAPI | Flask | Django |
---|---|---|---|
异步支持 | 原生支持 | 需扩展(Quart) | 需扩展(Channels) |
性能 | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐ |
学习曲线 | 中等 | 简单 | 复杂 |
内置功能 | API 核心功能 | 轻量级基础 | 全栈功能(ORM、Admin) |
文档生成 | 自动 OpenAPI | 需插件 | 需第三方库 |
适用场景 | 高性能 API、微服务 | 小型应用、原型开发 | 复杂 Web 应用 |
数据库集成
asyncpg
(PostgreSQL)、aiomysql
(MySQL)。安全认证
Password
、Bearer
)、OpenID Connect。python-jose
(JWT 编码)、passlib
(密码哈希)。部署与监控
扩展库
fastapi-cache
:Redis/Memcached 缓存。fastapi-users
:用户认证系统。fastapi-utils
:重复任务、定时端点。通过前言可见,FastAPI 是 Python 生态中构建现代化 API 的首选框架,兼顾开发效率与运行时性能,适用于从初创项目到企业级系统的广泛场景。下面将从FastAPI各技术面进行深入讲解:
# 架构示意图伪代码
Request -> [ASGI Server] -> [FastAPI App]
-> [Route]
-> [Dependencies]
-> [Endpoint]
-> [Response Model]
-> [OpenAPI Docs]
核心组件:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {
"message": "Hello World"}
@app.get("/items/{item_id}")
async def read_item(
item_id: int, # 路径参数
q: str = None, # 查询参数
short: bool = False # 类型转换
):
item = {
"item_id": item_id}
if q:
item.update({
"q": q})
if not short:
item.update({
"description": "This is an amazing item"})
return item
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.post("/items/")
async def create_item(item: Item) -> Item: # 输入输出模型
item_dict = item.dict()
if item.tax:
total = item.price + item.tax
item_dict.update({
"total": total})
return item_dict
from fastapi import Depends
# 简单依赖
def query_extractor(q: str = None):
return q
# 复杂依赖项
def complex_dependency(
q: str = Depends(query_extractor),
last_query: str = Cookie(None)
):
return {
"q": q, "last_query": last_query}
@app.get("/dependencies/")
async def read_query(dependency: dict = Depends(complex_dependency)):
return dependency
from fastapi.security import OAuth2PasswordBearer
from passlib.context import CryptContext
# 密码加密
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# OAuth2 流程
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def get_current_user(token: str = Depends(oauth2_scheme)):
user = decode_token(token) # 实现解码逻辑
return user
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
/myapi
/routers
items.py
users.py
/models
base.py
items.py
/dependencies
database.py
/utils
security.py
main.py
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "postgresql+asyncpg://user:password@localhost/db"
engine = create_async_engine(SQLALCHEMY_DATABASE_URL)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession)
async def get_db():
async with AsyncSessionLocal() as session:
yield session
@app.post("/users/")
async def create_user(
user: UserCreate,
db: AsyncSession = Depends(get_db)
):
db_user = User(**user.dict())
db.add(db_user)
await db.commit()
return db_user
import httpx
async def call_external_api():
async with httpx.AsyncClient() as client:
response = await client.get("https://api.example.com/data")
return response.json()
@app.get("/external-data")
async def get_data():
return await call_external_api()
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.decorator import cache
@app.on_event("startup")
async def startup():
FastAPICache.init(RedisBackend("redis://localhost"))
@app.get("/cached-data")
@cache(expire=60)
async def get_cached_data():
# 执行复杂计算
return {
"data": complex_calculation()}
from fastapi.testclient import TestClient
client = TestClient(app)
def test_read_item():
response = client.get("/items/42?q=test")
assert response.status_code == 200
assert response.json() == {
"item_id": 42,
"q": "test"
}
# 使用 Gunicorn + Uvicorn 部署
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
# 设置性能参数
gunicorn --bind 0.0.0.0:80 \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--timeout 120 \
main:app
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://example.com"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
from fastapi_limiter import FastAPILimiter
from fastapi_limiter.depends import RateLimiter
@app.on_event("startup")
async def startup():
FastAPILimiter.init(RedisBackend("redis://localhost"))
@app.get("/limited", dependencies=[Depends(RateLimiter(times=2, seconds=5))])
async def limited_route():
return {
"detail": "Rate limited endpoint"}
# main.py
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
class UserCreate(BaseModel):
username: str
password: str
email: Optional[str] = None
class UserInDB(UserCreate):
hashed_password: str
def fake_hash_password(password: str):
return "hashed_" + password
def fake_save_user(user_in: UserCreate):
hashed_password = fake_hash_password(user_in.password)
user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
print("User saved.. (not really)")
return user_in_db
@app.post("/users/", response_model=UserInDB)
async def create_user(user_in: UserCreate):
user_saved = fake_save_user(user_in)
return user_saved
#