python-dependency-injector icon indicating copy to clipboard operation
python-dependency-injector copied to clipboard

Ressource not closed in case of Exception in the function

Open BaptisteSaves opened this issue 2 years ago • 1 comments
trafficstars

Hello,

We have some function that uses Closing[Provide["session"]] to inject the database session to the method. It works well, except if we have any exception raised in the function the closing method will not be called and the resource will stay open

This is really easy to reproduce with a minimal case on fastAPI, the shudown (db.close()) is never called in this case.

This is a huge problem as in the next call, the injector will re inject the resource (the session) which is already in a fail state.

I did not find anything on the documentation regarding error management, did we miss something ?

Thanks for your help.

Container

class Container(containers.DeclarativeContainer):
    wiring_config = containers.WiringConfiguration(packages=[XX])

    session = providers.Resource(get_db)

Resource DB:

def get_db() -> Iterator[Session]:
    db: Session = SessionMaker()
    try:
        yield db
    finally:
        db.close()

Router:

@router.get(
    "/hello-world"
)
@inject
async def hello_world(
    session: Session = Depends(Closing[Provide["session"]]),
):
    raise Exception()

BaptisteSaves avatar Mar 20 '23 16:03 BaptisteSaves

@rmk135 Any thoughts on that please ? I would really like to use the library that seems awesome but this is a blocker if we cannot close our session at the end of the call. :pray:

BaptisteSaves avatar Mar 30 '23 11:03 BaptisteSaves