有時,我們要為整個應用添加依賴項。通過與定義FastAPI 學習之路(二十五)路徑操作裝飾器依賴項
類似的方式,可以把依賴項添加至整個 FastAPI 應用。
那么我們看下,如何去實現,比如我們全局都需要校驗token。我們去看下,我們應該如何實現代碼。
from fastapi import FastAPI,Header, HTTPException,Depends fake_items_db = [{"city": "beijing"}, {"city": "shanghai"}, {"city": "heze"}] def verify_token(token: str = Header(...)): if token!="leizishuoceshikaifa": raise HTTPException(status_code=400, detail="Token header invalid") app = FastAPI(dependencies=[Depends(verify_token)]) @app.get("/items/") def read_items(): return fake_items_db @app.get("/item/") def read_item(city:str): for item in fake_items_db: if item['city']==city: return item return {"msg":"not exict"}
那么我們看下,接口是否都需要token。
測試items
我們增加下token
我們去測試下帶參數
我們帶下token
文章首發在公眾號,歡迎關注。