赞
踩
from typing import Optional from fastapi import APIRouter, Header, HTTPException, Depends # app13 = APIRouter() """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}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。