在 FastAPI 中使用 Depends 比仅调用依赖函数/类有什么优势?

Ojo*_*mio 17 python dependency-injection fastapi

FastAPI通过自己的依赖解析机制提供了一种管理依赖的方法,比如数据库连接。

它类似于pytest夹具系统。简而言之,您在函数签名中声明您需要的内容,FastAPI 将调用您提到的函数(或类)并在调用处理程序时注入正确的结果。

是的,它确实缓存(在单个处理程序运行期间),但是我们不能仅使用@lru_cache装饰器并在每次运行时简单地调用这些依赖项来实现相同的功能吗?我错过了什么吗?

Gab*_*lli 14

FastAPI 还会将请求中的参数注入到您的依赖项中,并将它们包含在 OpenApi 规范中。

这允许您重用参数,这可以帮助您编写更少的代码,尤其是当您的项目变大时。

如果没有依赖注入,您每次都必须在每条路线上指定参数。

在来自FastAPI 文档的这个示例中,我们共享了常见的搜索参数。

async def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons

@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
    return commons
Run Code Online (Sandbox Code Playgroud)