python-3.x - 具有依赖注入器 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 - 发现每个职业的男性比例并将其从高到低排序
- javascript - 框、线性渐变、css 和 javascript
- javascript - 如何在 iframe 中捕获重定向的 URL?
- javascript - 如何在 Angular 中使搜索不区分大小写
- bpmn - 可用于创建 BPMN 文件的工具
- reactjs - 如何防止用户在“react-datePicker”中选择大于结束日期的开始日期?
- php - centos7 ssh 主机密钥验证失败
- java - Apache POI - 如何在 Word 文档的表格中均匀分布列和行
- android - 无法动态更改 GridView
- python - 检查是否存在与列表中的字符串匹配的子字符串