其他分享
首页 > 其他分享> > FastAPI(33)- Global Dependencies 全局依赖

FastAPI(33)- Global Dependencies 全局依赖

作者:互联网

背景

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

 

FastAPI 类的 dependences 参数

 

实际代码

#!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)

 

查看 Swagger API 文档

 

正确请求 /items 的结果

 

验证失败 /users 的结果

 

标签:return,33,FastAPI,app,Global,Depends,token,key
来源: https://www.cnblogs.com/poloyy/p/15334280.html