3

Let's consider the following code

class CommonDependency:
    ...


@app.on_event("startup")
async def start():
    parser = ArgumentParser(...)
    ... # here dep are init with command line arguments
    return dep

@app.get("/")
async def root(dep = Depends(start)):
    ... # here dep is needed
    return ...

The start function needs to be run at startup because it will make use of command line arguments in order to create the dependencies.

The problem is that dep is some stateful object that should share its state across all requests since boot.

The solution is declare dep in the module scope

dep = CommonDependency(...)

@app.on_event("startup")
async def start():
   dep.property = ... # here the property contains the init dependency that we need

and overwrite a property declared inside the class to be accessed through all the module functions.

However, doing that, Depends became useless because the dep object is visible by all functions.

I really don't like this approach, is there any better solution?

Antonio Santoro
  • 827
  • 1
  • 11
  • 29
  • You can store it in app state that accessible via `request.app` https://www.starlette.io/applications/#storing-state-on-the-app-instance – alex_noname Aug 06 '21 at 17:18
  • So is there no alternatives for stateful objects? – Antonio Santoro Aug 06 '21 at 17:23
  • IMO, Python's duck typing eliminates the need for a dependency injection" concept (as defined here https://en.wikipedia.org/wiki/Dependency_injection). I also think that this "Depends" mechanics is just masking a global callable. I am new to FastAPI, so maybe there is some extra handling for making async calls, who knows. – Florin C. Jan 05 '22 at 17:39
  • Just found this answer which explains why Depends is needed in FastAPI: https://stackoverflow.com/a/64810270/7373966 – Florin C. Jan 05 '22 at 17:48

0 Answers0