FastAPI(33)- Global Dependencies 全局依赖

简介: FastAPI(33)- Global Dependencies 全局依赖

背景


对于某些实际应用场景,希望向整个应用程序添加一个全局依赖项

 

FastAPI 类的 dependences 参数


image.png

  • 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, APIRouter
# 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 = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
@app.get("/items/")
async def read_items():
    return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
@app.get("/users/")
async def read_users():
    return [{"username": "Rick"}, {"username": "Morty"}]
if __name__ == "__main__":
    uvicorn.run(app="29_global_depends:app", host="127.0.0.1", port=8080, reload=True, debug=True)


  • 在实例化 FastAPI 的时候传 dependences 参数,就可以声明全局依赖项啦
  • 发起的所有请求都会先执行全局依赖项,然后再执行对应的路径操作函数

 

查看 Swagger API 文档

image.png

image.png


正确请求 /items 的结果

image.png

验证失败 /users 的结果

image.png

相关文章
|
Python
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器
261 0
|
关系型数据库 MySQL 数据库连接
FastAPI(34)- Dependencies with yield 依赖项中使用 yield
FastAPI(34)- Dependencies with yield 依赖项中使用 yield
210 0
FastAPI(34)- Dependencies with yield 依赖项中使用 yield
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 子依赖
|
IDE API 开发工具
FastAPI(30)- Classes as Dependencies 类依赖注入 (下)
FastAPI(30)- Classes as Dependencies 类依赖注入 (下)
114 0
FastAPI(30)- Classes as Dependencies 类依赖注入 (下)
|
IDE API 开发工具
FastAPI(30)- Classes as Dependencies 类依赖注入 (上)
FastAPI(30)- Classes as Dependencies 类依赖注入 (上)
219 0
FastAPI(30)- Classes as Dependencies 类依赖注入 (上)
|
NoSQL 关系型数据库 数据库连接
FastAPI(29)- Dependencies 依赖注入的初步使用
FastAPI(29)- Dependencies 依赖注入的初步使用
403 0
FastAPI(29)- Dependencies 依赖注入的初步使用
FastAPI 学习之路(二十六)全局依赖项
FastAPI 学习之路(二十六)全局依赖项
FastAPI 学习之路(二十六)全局依赖项
|
测试技术
FastAPI 学习之路(二十五)路径操作装饰器依赖项
FastAPI 学习之路(二十五)路径操作装饰器依赖项
FastAPI 学习之路(二十五)路径操作装饰器依赖项
|
缓存
FastAPI 学习之路(二十四)子依赖项
FastAPI 学习之路(二十四)子依赖项
FastAPI 学习之路(二十四)子依赖项