Fastapi之依赖注入系统

1.函数依赖注入简单示例

from typing import Optional

import uvicorn
from fastapi import FastAPI, Depends


async def common_parameters(q: Optional[str] = None, page: int = 0, limit: int = 10):
    return {"query": q, "page": page, "limit": limit}


@app.get('/dependency')
async def dependency(common: dict = Depends(common_parameters)):
    print(common.get("query"))
    return common


if __name__ == '__main__':
    uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True,
                debug=True, workers=1)

2.类依赖注入简单示例

from typing import Optional

import uvicorn
from fastapi import FastAPI, Depends


class CommonQueryParams:
    def __init__(self, q: Optional[str] = None, page: int = 0, limit: int = 10):
        self.query = q
        self.page = page
        self.limit = limit


@app.get('/dependency01')
# async def dependency01(common: CommonQueryParams = Depends(CommonQueryParams)):
# async def dependency01(common: CommonQueryParams = Depends()):
async def dependency01(common=Depends(CommonQueryParams)):
    print(common.query)
    return common

3.子依赖注入简单示例

from typing import Optional

import uvicorn
from fastapi import FastAPI, Depends

app = FastAPI()

def query(q: Optional[str] = None):
    # 可以对q进行处理
    return q


def sub_query(q: str = Depends(query), last_query: Optional[str] = None):
    if not q:
        return last_query
    return q


@app.get("/sub_dependency")
async def sub_dependency(final_query: str = Depends(
    sub_query,
    # 默认就是True,表示当多个依赖有一个共同的子依赖时,每次request请求只会调用一次子依赖,多次调用则从缓存中获取
    use_cache=True
)):
    return {"sub_query": final_query}


if __name__ == '__main__':
    uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True,
                debug=True, workers=1)

4.在路径操做中调用依赖

from typing import Optional

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

app = FastAPI()


async def verify_key(x_key: str = Header(...)):
    if x_key != "fake-super-key":
        raise HTTPException(status_code=400, detail="X-Key header invalid")
    return x_key


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


# 在路径操做中调用依赖
@app.get("/dependency_in_path_operation", dependencies=[Depends(verify_key), Depends(verify_token)])
async def dependency_in_path_operation():
    return [{"user": "user01"}, {"user": "user02"}]


if __name__ == '__main__':
    uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True,
                debug=True, workers=1)

5.全局依赖

from fastapi import FastAPI, Depends

app = FastAPI(
    title="FastAPI Tutorial",   # 文档标题
    description="FastAPI接口文档,项目代码:https://github.com/xxxx",  # 文档描述
    version='1.0.0',  # 版本描述
    docs_url='/docs',  # 文档路径
    redoc_url='/readme_docs',  # redoc文档路径
    dependencies=[Depends(verify_key), Depends(verify_token)]
)
posted @ 2022-06-27 16:38  fatpuffer  阅读(275)  评论(0编辑  收藏  举报