question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Help please. I'm not getting the correct way to do the wiring

See original GitHub issue

I am trying to use wiring into my fastapi project. This is my file layout

micro_servicio
├── adapters
│   ├── db
│   │   └── __init__.py
│   ├── __init__.py
│   └── web
│       ├── app.py
│       ├── __init__.py
│       └── routers
│           ├── __init__.py
│           └── test.py
├── core
│   ├── acciones
│   │   └── __init__.py
│   └── __init__.py
├── __init__.py
└── run.py

I have my business logic in core package and use the adapters packages to connect de core with the exterior, like an hexagonal architecture.

run.py

import uvicorn
# from micro_servicio.adapters.web import app


if __name__ == "__main__":
    uvicorn.run("micro_servicio.adapters.web.app:app", host="0.0.0.0", port=8001, reload=True, log_level='debug')

micro_servicio.core.init.py

from dependency_injector import containers, providers
from micro_servicio.core.acciones import Acciones


class Container(containers.DeclarativeContainer):
    # wiring_config = containers.WiringConfiguration(modules=[Acciones]) <---- does not work either
    config = providers.Configuration()
    acciones = providers.Factory(Acciones)

micro_servicio.core.acciones.init.py


class Acciones:
    def __init__(self):
        pass

    def accion_uno(self, param1: int, param2: str) -> str:
        return {'msg': '{}, {} veces!!!'.format(param2, param1)}

micro_servicio.adapters.web.app.py

"""Application module."""

from fastapi import FastAPI
from dependency_injector.wiring import register_loader_containers
from micro_servicio.core import Container
from micro_servicio.core.acciones import Acciones
from micro_servicio.adapters.web.routers.test import router as r_test


def create_app() -> FastAPI:
    container = Container()
    # register_loader_containers(container) <---- does not work either
    container.wire(modules=[Acciones])

    app = FastAPI(debug=True, title='Esto es una prueba')
    app.container = container
    app.include_router(r_test)
    return app


app = create_app()

micro_servicio.adapters.web.routers.test.py

from typing import Optional, List
from fastapi import APIRouter, Depends, Response, status
from dependency_injector.wiring import inject, Provide
from micro_servicio.core.acciones import Acciones
from micro_servicio.core import Container

router = APIRouter()


@router.get("/")
async def index():
    print("llegue hasta el router index endpoint")
    return {'msg': 'Hola mundo'}


@router.get("/test")
@inject
async def index(
    acciones: Acciones = Depends(Provide[Container.acciones])
):
    print("llegue hasta el router test endpoint")
    return acciones.accion_uno(4, "hola")   # This returns AttributeError: 'Provide' object has no attribute 'accion_uno'
   

No matter what method I use to do the wiring the only way I get it work is this:

return acciones.provider().accion_uno(4, "hola")

What I am doing wrong???

Thanks in advance Nomar Mora

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
danodiccommented, Apr 25, 2022

Hello, just would like to mention that I have been facing the same issue. The version of the lib I am using is 4.39.1.

I have followed the instructions exactly as mentioned at https://python-dependency-injector.ets-labs.org/examples/fastapi.html but I was still getting the error. Instead of providing the dependency, it provides an instance of the Provide marker when my route is called.

After some investigation, I was able to find that I could do the wiring manually as mentioned in the wiring docs as follows;

from fastapi import FastAPI

from application.deps import DependencyContainer
from application.routes.content import content_router


def get_app() -> FastAPI:
    app = FastAPI()
    app.include_router(content_router)

    # The manual wiring saved the day :)
    DependencyContainer().wire(modules=['application.routes.content'])

    return app

That solved the issue. Setting the WiringConfiguration inside my container did not change anything.

I was not able to find what would be the fix, but I hope that helps finding a solution.

1reaction
kalimalrazifcommented, Jun 1, 2022

Thanks @danodic! Thank you so much!

I misunderstood what I should put in the wiring configuration!

I reread everything and now it worked for me!!!

Read more comments on GitHub >

github_iconTop Results From Across the Web

How To Fix Short Wires Inside Electrical Boxes! DIY Tip And ...
DIY Tip And Trick Methods For Beginners! DO YOU HAVE QUESTIONS ON YOUR HOME REPAIR OR DIY PROJECT? GET TIPS, ADVICE AND ANSWERS!...
Read more >
BIGGEST Mistakes DIYers Make When Connecting Wires ...
In this video I will show you some of the most common mistakes DIYers make when they are connecting or splicing wires together....
Read more >
How To Wire A Room For Electricity - Bedroom Wiring Rough In
I take you step by step on how to rough in a bedroom wiring. House wiring for electricity i... ... Your browser can...
Read more >
Tricks to Find and Fix Electrical Problems in your wall. #2
Tips that electricians use to fix electrical problems. #2 Basic Residential Electricity.https://youtu.be/ILvrVxVrraI BASIC RESIDENTIAL ...
Read more >
Find the correct wiring for a 3-way switch in 2-minutes!
How to determine the correct wires to attach to a 3- way switch when the wire and screw terminal color code is not...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found