FastAPI(32)- Dependencies in path operation 通过路径操作装饰器的 dependencies 参数声明依赖
FastAPI(32)- Dependencies in path operation 通过路径操作装饰器的 dependencies 参数声明依赖 
背景
- 在某些实际场景中,并不需要使用依赖项的返回值,或者依赖项没有返回值,但仍需要执行这个依赖项
 - 针对这种场景,可以向路径操作装饰器的 dependencies 参数传入依赖项,而不使用 Depends()
 
dependences 参数
- dependences 类型指定为 Optional[Sequence[Depends]]
 - Sequence 是序列,不仅可以接收 List,还可以接收 Set、Tuple 等
 - 子类型就是 Depends
 
实际栗子
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/9/25 12:52 下午
# file: 28_path_depends.py
"""
from typing import Optional
import uvicorn
from fastapi import Depends, FastAPI, HTTPException, Header
app = FastAPI()
# 1、第一个依赖,验证请求头中的 x_token
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")
    # 没有 return
# 2、第二个依赖,验证请求头中的 x_key
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
    return x_key
@app.get("/items",
         dependencies=[
             # 声明了两个依赖,是一个数组哦
             Depends(verify_token),
             Depends(verify_key)]
         )
async def read_item():
    return [{"item": "Foo"}, {"item": "Bar"}]
if __name__ == "__main__":
    uvicorn.run(app="28_path_depends:app", host="127.0.0.1", port=8080, reload=True, debug=True) 
- 虽然第二个依赖项有 return 值,但是并不会传递给路径操作函数,所以 return 不 return 没什么区别
 - 即使不使用依赖项的 return 值,该依赖项仍然会被调用
 
重点总结
@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
通过路径操作装饰器的 dependences 参数声明依赖,并不会使用依赖项的返回值
async def read_query(query_or_default: str = Depends(query_or_cookie_extractor)):
    pass
通过函数参数来声明依赖,会将依赖项的返回值赋值给参数使用
查看 Swagger API 文档
正确传参的请求结果
依赖项校验失败的请求结果





                
            
        
浙公网安备 33010602011771号