深入探索FastAPI依赖注入与微服务构建
1. 依赖注入相关
在使用FastAPI进行开发时,依赖注入是一个重要的概念。FastAPIIntegration实例有一个 depends() 方法,可用于执行注入操作。像Lagom这样的第三方模块,具有易于无缝集成到任何框架的特性,在进行依赖注入时,甚至可以不再需要FastAPI的 Depends() 函数。以下是一个示例代码:
@router.post("/complaint/recipe")
def report_recipe(rid: UUID,
complaintservice=deps.depends(BadRecipeRepository)):
complaintservice.add_bad_recipe(rid)
return JSONResponse(content={"message":
"reported bad recipe"}, status_code=201)
在上述代码中, report_recipe() 函数将 BadRecipeRepository 作为可注入服务。由于它是容器的一部分,Lagom的 depends() 函数会在容器中搜索该对象,并将其连接到API服务,以将投诉信息保存到字典数据存储中。
FastAPI中依赖项的作用
超级会员免费看
订阅专栏 解锁全文
1355

被折叠的 条评论
为什么被折叠?



