FastAPI 学习之路(二十五)路径操作装饰器依赖项

简介: FastAPI 学习之路(二十五)路径操作装饰器依赖项

   有时,我们并不需要在路径操作函数中使用依赖项的返回值。或者说,有些依赖项不返回值。


但仍要执行或解析该依赖项。


对于这种情况,不必在声明路径操作函数的参数时使用 Depends,而是可以在路径操作装饰器中添加一个由 dependencies 组成的 list。


     我们看下,如何去实现。我们去校验下请求头中的token,请求的key。


from fastapi import  FastAPI,Header, HTTPException,Depends
app = FastAPI()
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")
def verify_key(key: str = Header(...)):
    if key != "key":
        raise HTTPException(status_code=400, detail="Key header invalid")
    return key
@app.get("/items/",dependencies=[Depends(verify_token),Depends(verify_key)])
def read_items():
    return fake_items_db


我们看下结果如何。      


 用例1:不传入请求头


image.png


我们去看下带上请求头中的token


image.png


  我们去带下key,这样接口返回就是正确的。


image.png


我们可以看到无论路径装饰器依赖项是否返回值,路径操作都不会使用这些值。但是这些值都必须携带。



相关文章
|
SQL Oracle 关系型数据库
FastAPI数据库系列(一) MySQL数据库操作 一、简介
FastAPI中你可以使用任何关系型数据库,可以通过SQLAlchemy将其轻松的适应于任何的数据库,比如: PostgreSQL MySQL SQLite Oracle Microsoft SQL Server ...
|
4天前
|
Python
Fastapi进阶用法,路径参数,路由分发,查询参数等详解
Fastapi进阶用法,路径参数,路由分发,查询参数等详解
|
Python
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器
261 0
|
存储 IDE 中间件
FastAPI(44)- 操作关系型数据库(下)
FastAPI(44)- 操作关系型数据库(下)
385 0
|
SQL 关系型数据库 MySQL
FastAPI(44)- 操作关系型数据库(上)
FastAPI(44)- 操作关系型数据库(上)
280 0
FastAPI(33)- Global Dependencies 全局依赖
FastAPI(33)- Global Dependencies 全局依赖
299 0
FastAPI(33)- Global Dependencies 全局依赖
FastAPI(32)- Dependencies in path operation 通过路径操作装饰器的 dependencies 参数声明依赖
FastAPI(32)- Dependencies in path operation 通过路径操作装饰器的 dependencies 参数声明依赖
141 0
FastAPI(32)- Dependencies in path operation 通过路径操作装饰器的 dependencies 参数声明依赖
|
缓存 API
FastAPI(31)- Sub-dependencies 子依赖
FastAPI(31)- Sub-dependencies 子依赖
120 0
FastAPI(31)- Sub-dependencies 子依赖