FastAPI Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。
pip install fastapi uvicorn
uvicorn main:app --reload
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello FastAPI"}
uvicorn main:app --reload
@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 pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
def create(item: Item):
return item
@app.post("/items/", response_model=Item)
def create(item: Item):
return item
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}
from fastapi import HTTPException
@app.get("/err")
def error():
raise HTTPException(404, "Not Found")
from fastapi import FastAPI
@app.get("/json")
def get_data():
return {"status": "ok"}
from fastapi.staticfiles import StaticFiles
app.mount("/static", StaticFiles(directory="static"), name="static")
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates("templates")
from fastapi import APIRouter
router = APIRouter()
@router.get("/")
def admin():
return {"admin": True}
app.include_router(router, prefix="/admin")
project/
├── main.py
├── static/
├── templates/
├── routers/
│ └── admin.py
└── models/
/docs/redocfrom fastapi import status
@app.post("/create", status_code=status.HTTP_201_CREATED)
def create():
return {"msg": "Created"}
地址
Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)Level 2, 171 La Trobe St, Melbourne VIC 3000四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号Business Hub, 155 Waymouth St, Adelaide SA 5000Disclaimer
JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.
匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议
© 2017-2025 JR Academy Pty Ltd. All rights reserved.
ABN 26621887572