FastAPI是一種現(xiàn)代、高性能的Python Web框架,用于構(gòu)建Web應(yīng)用程序和API。
它基于Python的異步編程庫asyncio和await語法,以及類型注解和自動(dòng)文檔生成等特性,提供了快速、易用和可靠的開發(fā)體驗(yàn),接下來本文將介紹10項(xiàng)被忽視的FastAPI實(shí)用功能。
FastAPI支持定義“依賴項(xiàng)”,這些依賴項(xiàng)會(huì)被解析并注入到路徑操作中。使用這個(gè)功能處理常見任務(wù),如數(shù)據(jù)庫連接或用戶身份驗(yàn)證。
def get_db(): db = SessionLocal() try: yield db finally: db.close()@app.get("/users/{user_id}")def read_user(user_id: int, db: Session = Depends(get_db)): user = db.query(User).get(user_id) return user
使用Pydantic模型聲明響應(yīng)結(jié)構(gòu)。這將自動(dòng)生成API文檔并驗(yàn)證響應(yīng)數(shù)據(jù)。
class User(BaseModel): id: int name: str@app.get("/users/{user_id}", response_model=User)def read_user(user_id: int): ...
拋出帶有狀態(tài)代碼和詳細(xì)信息的HTTP異常,以處理不同的HTTP狀態(tài)代碼。
@app.get("/items/{item_id}")def read_item(item_id: str): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") return {"item": items[item_id]}
使用轉(zhuǎn)換器將路徑參數(shù)轉(zhuǎn)換為所需的Python數(shù)據(jù)類型。
@app.get("/items/{item_id}")def read_item(item_id: int): ...
將需要長期運(yùn)行的任務(wù)委托給后臺(tái),以釋放API的響應(yīng)時(shí)間。
@app.post("/send-notification/{email}")async def send_notification(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(send_email, email=email) return {"message": "Notification sent in the background"}
使用Query聲明字符串查詢參數(shù)和驗(yàn)證。
@app.get("/items/")async def read_items(q: Optional[str] = Query(None, max_length=50)): results = {"items": [{"item_id": "Foo"}]} if q: results.update({"q": q}) return results
FastAPI內(nèi)置了OAuth2密碼和Bearer,用于處理用戶注冊、登錄和令牌檢索的所有路徑。
@app.post("/token", response_model=Token)def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) return {"access_token": access_token, "token_type": "bearer"}
FastAPI使用Pydantic進(jìn)行數(shù)據(jù)驗(yàn)證和序列化,提供了一種處理錯(cuò)誤和復(fù)雜類型的簡單方式。
class Item(BaseModel): name: str description: str@app.post("/items/")async def create_item(item: Item): return item
FastAPI支持使用Starlette的TestClient編寫簡潔的測試用例。
from starlette.testclient import TestClientdef test_read_main(): client = TestClient(app) response = client.get("/") assert response.status_code == 200
FastAPI通過Swagger UI和ReDoc提供自動(dòng)交互式API文檔。只需訪問/docs或/redoc路由即可訪問這些文檔。
本文鏈接:http://www.tebozhan.com/showinfo-26-14821-0.html十個(gè)容易被忽視的FastAPI實(shí)用功能
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com