精选 FastAPI 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。FastAPI 是一个快速、现代的 Python 3.7+ Web 框架,用于构建 API 的简明速查表。
@app.get("/items/{id}")
def read(id: int):
return {"id": id}
@app.get("/search")
def find(q: str = "default"):
return {"q": q}
@app.get("/filter")
def filter_data(limit: int = 10, active: bool = True):
return {"limit": limit, "active": active}
from fastapi import Form
@app.post("/login")
def login(user: str = Form(...)):
return {"user": user}
from fastapi import UploadFile, File
@app.post("/upload")
def upload(f: UploadFile = File(...)):
return {"filename": f.filename}
from fastapi import Header, Cookie
@app.get("/info")
def info(ua: str = Header(None)):
return {"UA": ua}
@app.middleware("http")
async def log_req(req, call_next):
res = await call_next(req)
return res
from fastapi import Depends
def auth(token: str = ""):
if token != "xyz": raise HTTPException(401)
return True
@app.get("/secure")
def secure(_: bool = Depends(auth)):
return {"secure": True}