[FastAPI-33]依赖注入-路径装饰器-全局

1. 路径装饰器

from fastapi import FastAPI, Header, HTTPException, Depends,status

app = FastAPI()

def verify_token(x_token: str = Header()):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="X-Token header invalid")
    # return x_token


@app.get("/items/", dependencies=[Depends(verify_token)])
def get_items():
    return [{"item": "Foo"}, {"item": "Bar"}]

2. 全局

from fastapi import Depends, FastAPI, Header, HTTPException


def verify_token(x_token: str = Header()):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")


app = FastAPI(dependencies=[Depends(verify_token)])


@app.get("/items/")
def get_items():
    return [{"item": "Portal Gun"}, {"item": "Plumbus"}]


@app.get("/users/")
def get_users():
    return [{"username": "Rick"}, {"username": "Morty"}]
posted @ 2023-03-26 21:03  LeoShi2020  阅读(113)  评论(0编辑  收藏  举报