具有依赖注入器Python的快速API获取strategy_service.test(Test(name, id)) AttributeError:“Provide”对象没有属性“test”

Pra*_*lam 7 rest dependency-injection python-3.x fastapi

我正在使用 FastApI 和依赖注入器,下面是项目结构

-app 
    - api/v1/endpoints
    - repository
    - service
    main.py
Run Code Online (Sandbox Code Playgroud)

当我将依赖项注入端点时,我总是得到提供对象而不是实际的类对象,因为此代码总是抛出

AttributeError:“提供”对象没有属性“测试” 但是,如果我在正常函数中注入依赖项,它会很好地工作。

下面是我正在使用的代码片段 -

users.py 作为端点

@router.get('/u/{name}/{id}')
def add_user(name:str, id:int, strategy_service:StrategyService = Depends(Provide[Container.strategy_service])):
    strategy_service.test(Test(name, id))
Run Code Online (Sandbox Code Playgroud)

集装箱级

class Container(DeclarativeContainer):
    #Define configuration
    config = providers.Configuration()

    #Database
    db = providers.Singleton(Database, db_url=config.db_url)
    
    #All the repositories Configuration
    strategy_repository = providers.Factory(
        StrategyRepository,
        session_factory = db.provided.session
    )

#All the services configured
    strategy_service = providers.Factory(
        StrategyService,
        strategy_repository = strategy_repository
    )
Run Code Online (Sandbox Code Playgroud)

主要.py

    def create_app() -> FastAPI:
        container = Container()
        container.config.from_yaml('../config.yml')
         container.wire(packages=[api])
   
    
        app = FastAPI()
    
        app.container = container
    
        #Here configure all your routes
        app.include_router(api_v1.router, prefix='/api/v1')
    
        #Return the final app
        return app
    
    app = create_app()

if __name__ == '__main__':
    #We can get this host and port number from config files
    uvicorn.run(app, host = '127.0.0.1', port = 8080)
Run Code Online (Sandbox Code Playgroud)

得到这个异常 -

结果 = self.fn(*self.args, **self.kwargs) 文件“/Users/manpr06/driveE/AlgoBot/algotradersbot-service/app/api/v1/endpoints/users.py”,第 21 行,在 add_user 中Strategy_service.test(Test(name, id)) AttributeError: 'Provide' 对象没有属性 'test'

有人可以帮忙吗?

小智 0

我不知道它是否直接相关,但在我将依赖注入器从 4.39.1 降级到 4.38.0 后,它解决了这个问题并开始工作。希望能帮助到你!