FastAPI 的详细用法介绍,涵盖其核心功能、常用技巧和最佳实践。FastAPI 是一个现代、高性能的 Python Web 框架,基于 Starlette 和 Pydantic,支持异步编程,适合构建 API 和 Web 应用。
pip install fastapi uvicorn[standard]
fastapi
: 核心框架。uvicorn
: ASGI 服务器,用于运行 FastAPI 应用。[standard]
: 安装额外依赖(如异步支持、文档工具等)。from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id, "name": "Sample Item"}
uvicorn main:app --reload
main
: 文件名(如 main.py
)。app
: FastAPI 实例的名称。--reload
: 开发模式下自动重新加载服务器。http://localhost:8000/docs
(Swagger UI)。http://localhost:8000/redoc
。HTTP 方法 | 装饰器 | 示例 |
---|---|---|
GET | @app.get() |
获取资源 |
POST | @app.post() |
创建资源 |
PUT | @app.put() |
更新资源 |
DELETE | @app.delete() |
删除资源 |
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
from pydantic import BaseModel
from typing import Optional
class Item(BaseModel):
name: str
price: float
description: Optional[str] = None
tax: Optional[float] = None
@app.post("/items/")
def create_item(item: Item):
return item
{
"name": "Foo",
"price": 45.2,
"description": "A very nice item",
"tax": 3.2
}
import asyncio
@app.get("/async")
async def async_example():
await asyncio.sleep(1) # 模拟 I/O 操作
return {"message": "Async response"}
@app.get("/db")
async def fetch_data():
data = await async_db_query() # 假设的异步数据库查询
return data
@app.middleware("http")
async def log_request_time(request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
print(f"请求路径: {request.url.path}, 处理时间: {process_time:.4f} 秒")
return response
itsdangerous
)。CORSMiddleware
)。from fastapi import Depends
def get_db():
db = "Database Connection"
try:
yield db
finally:
db.close()
@app.get("/users/")
def read_users(db: str = Depends(get_db)):
return {"db": db}
from fastapi import File, UploadFile
@app.post("/uploadfile/")
def upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
from fastapi import Form
@app.post("/login")
def login(username: str = Form(...), password: str = Form(...)):
return {"username": username}
from fastapi import HTTPException
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id < 0:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
from fastapi import FastAPI, HTTPException
from starlette.exceptions import HTTPException as StarletteHTTPException
@app.exception_handler(StarletteHTTPException)
def custom_http_exception_handler(request, exc):
return JSONResponse({"error": exc.detail}, status_code=exc.status_code)
from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}
from fastapi import BackgroundTasks
def write_log(message: str):
with open("log.txt", "a") as f:
f.write(message + "\n")
@app.post("/send-notification/")
def send_notification(background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, "Notification sent")
return {"message": "Notification sent in background"}
from fastapi import WebSocket
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
uvicorn main:app --host 0.0.0.0 --port 8000
async def
和 await
。Cache-Control
。遵循 RESTful 风格:
/users
)。自动生成文档:
类型提示:
模块化设计:
APIRouter
组织代码。