ets-labs / python-dependency-injector

Dependency injection framework for Python
https://python-dependency-injector.ets-labs.org/
BSD 3-Clause "New" or "Revised" License
3.89k stars 304 forks source link

FastAPI: AttributeError: 'Provide' object has no attribute 'test_message' #729

Closed MaxiPigna closed 1 year ago

MaxiPigna commented 1 year ago

Hello folks! I get the error AttributeError: 'Provide' object has no attribute 'test_message' This is the code

containers.py

from dependency_injector import containers, providers
from services.conversationService import ConversationService

class Container(containers.DeclarativeContainer):
    conversationService = providers.Factory(
        ConversationService
    )

conversationBaseService.py

from abc import abstractmethod

class ConversationBaseService:
    @abstractmethod
    def test_message(self, message: str) -> str:
        pass

conversationService.py

from services.conversationBaseService import ConversationBaseService

class ConversationService(ConversationBaseService):
        def test_message(self, message: str) -> str:
            print("Not Implemented")
            return "Sorry"

main.py

from services.conversationBaseService import ConversationBaseService
from containers import Container
from fastapi import Depends, FastAPI
from dependency_injector.wiring import inject, Provide

container = Container()
app = FastAPI()

@app.post("/test")
@inject
def test_api(
    conversationService: ConversationBaseService = Depends(Provide[Container.conversationService])
    ):
    conversationService.test_message("Ciao")

Library versions: Name: dependency-injector Version: 4.41.0

Name: fastapi Version: 0.100.1

Did I forget to configure something? I checked the documentation, but I didn't find a solution. Actually, the published example doesn't seems to be correct/updated.

billsioros commented 1 year ago

Have you wired the modules? FYI I'm a noob myself šŸ˜Š

martlaf commented 1 year ago

Not the most familiar with injection with FastAPI, but you can try with dependency-injector 4.38.0, see here: https://github.com/ets-labs/python-dependency-injector/issues/672

MaxiPigna commented 1 year ago

Have you wired the modules? FYI I'm a noob myself šŸ˜Š

Correct, I moved the APIs in another module and added wiring_config = containers.WiringConfiguration(modules=["api.conversations"])

GGJdevelope commented 5 months ago

folder structure

app -llm --container.py --adapter ---input ----api -----v1 ------llm.py

    wiring_config = WiringConfiguration(packages=['app']) #not working
    wiring_config = WiringConfiguration(packages=['app.llm.adapter.input.api.v1]) #not working
    wiring_config = WiringConfiguration(packages=['app.llm.adapter.input.api.v1.llm']) #working āœ… path to file(this file is router which contain @injection decoration)

modules argument also working same