与只调用依赖函数/类相比,在FastAPI中使用依赖有什么优势? [英] What are the advantages of using Depends in FastAPI over just calling a dependent function/class?
本文介绍了与只调用依赖函数/类相比,在FastAPI中使用依赖有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
FastAPI提供way通过其自身的依赖项解析机制管理依赖项,如数据库连接。
它类似于pytest
夹具系统。
简而言之,您在函数签名中声明了所需的内容,FastAPI将调用您提到的函数(或类),并在调用处理程序时注入正确的结果。
是的,它确实进行缓存(在单个处理程序运行期间),但我们不能只使用@lru_cache
修饰器并在每次运行时简单地调用这些依赖项来实现相同的功能吗?
我错过了什么吗?
推荐答案
FastAPI还会将请求中的参数注入到您的依赖项中,并将它们包括在OpenApi规范中。
这允许您重复使用参数,从而帮助您编写更少的代码,特别是在项目变得更大的情况下。
如果没有依赖项注入,您每次都必须指定每条路由上的参数。
在FastAPI docs中的此示例中,我们共享了公共搜索参数。
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
这篇关于与只调用依赖函数/类相比,在FastAPI中使用依赖有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文