from typing import Optional
from fastapi import APIRouter, Header, HTTPException, Depends
"""Global Dependencies 全局依赖"""
async def verify_token(x_token: str = Header(...)):
"""没有返回值的子依赖"""
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
async def verify_key(x_key: str = Header(...)):
"""有返回值的子依赖,但是返回值不会被调用"""
if x_key != "fake-super-secret-key":
raise HTTPException(status_code=400, detail="X-Key header invalid")
return x_key
app13 = APIRouter(dependencies=[Depends(verify_token), Depends(verify_key)])
@app13.get("/dependency_in_path_operation",
dependencies=[Depends(verify_token), Depends(verify_key)])
async def dependency_in_path_operation():
return [{"user": "user01"}, {"user": "user02"}]
@app13.get("/query")
def page_limit(page: int = 1, limit: Optional[int] = None):
if limit:
return {"page": page, "limit": limit}
return {"page": page}