首页 > 解决方案 > 具有依赖注入器 Python 的快速 API 获取 strategy_service.test(Test(name, id)) AttributeError: 'Provide' object has no attribute 'test'

问题描述

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

-app 
    - api/v1/endpoints
    - repository
    - service
    main.py

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

AttributeError: 'Provide' 对象没有属性 'test' 但是,如果我在正常函数中注入依赖项,它工作得很好。

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

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))

容器类

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
    )

主文件

    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)

得到这个例外 -

结果 = 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'

有人可以帮忙吗?

标签: python-3.xdependency-injectionrestfastapi

解决方案


推荐阅读