繁体   English   中英

无法将依赖项注入到 FastAPI 端点

[英]Unable to inject dependencies to FastAPI endpoints

我已经配置了一个dependencies.py ,我在其中使用 python 的binder.bind(my_config)将一组依赖项注入到不同的服务中。 目标是能够轻松地将这些服务注入我的 API 的每个端点。 当我通过名称注入该服务后将该服务作为参数传递给我的端点时,问题就出现了。 所以:

import inject
from fastapi import APIRouter, HTTPException, Request, Depends

from src.services.chords import ChordsService

router = APIRouter(prefix="/chords")


@router.get("")
@inject.params(chords_service=ChordsService)
def get_chords(chords_service: ChordsService, req: Request, key: str, suffix: str = None, instrument: str = None):

    params = dict(req.query_params)
    return chords_service.get(params)

这不起作用,我尝试更改get_chords ' arguments 的顺序。 我所做的只是得到不同的错误,但出现最多的是 ChordsService 不是有效的 pydantic 字段类型。 我已经阅读了一些关于在 FastAPI 中使用 pydantic 的内容,我明白了为什么会出现这个错误,但是我一直在尝试注入这些服务......有没有办法做到这一点? 谢谢!

您可以直接使用来自 fastapi 的依赖注入。 我没有 IDE,所以语法可能是错误的,但您可以执行以下操作:

@lru_cache(max_size=1)
def get_chords_service():
    return ChordsService()

@router.get("")
def get_chords(chords_service: ChordsService=Depends(get_chords_service), req: Request ...

如果您希望到处都使用相同的ChordService实例,请使用此选项。 如果你每次都可以得到一个新的,它会变得更简单(你甚至不需要 getter 函数):

@router.get("")
def get_chords(chords_service: ChordsService=Depends(), req: Request ...

您可以像下面这样向APIRouter注入依赖项 -

router = APIRouter(prefix="/chords",
dependencies=[Depends(ChordsService)])

参见示例https://fastapi.tiangolo.com/tutorial/bigger-applications/#another-module-with-apirouter

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM