Fastapi: [QUESTION] dependency_overrides in production possible?

Created on 26 Nov 2019  路  3Comments  路  Source: tiangolo/fastapi

Description

Is this a pattern you can use for production?


def storage():
    return ...

def s3storage():
   return ...

app = FastAPI()
@app.get("/files/{name})
def get_item(name, storage = Depends(storage)):
    return storage.read(name)

if should_use_s3:
    app.dependency_override[storage] = s3storage

Context:
Let's say you'd like your app to support multiple providers for file storage, data bases, ...
The documentation talks about dependency_override mostly in the unit testing context.

By the way: Thank you for the great library!

question

All 3 comments

I would personally recommend avoiding the use of dependency_overrides for this kind of production-time configuration (e.g., given issue #737 which you also opened 馃槃, and seems like a clear bug to me), and instead bake the logic directly into app setup and/or the dependency functions themselves.

I view the primary benefit of dependency_overrides as giving you a way to inject mocks during testing; if you are going to have multiple possible configurations in production I think those should be built into the app in a first class way. Just my 2c though!

Thank you for your answer!

So is this what it could look like:

def db():
    if system == "A":
        return Postgres()
    else:
        return SQLite()

@app.get("/foo")
def get_foo(db=Depends(db)):
    return db.find_foos()

(something like tihs)

Would really appreciate a minimal example of such a run time switch! Maybe I don't see the ocean between the waves.

Thanks for the help here @dmontagu ! :cake: :bowing_man:

Thanks @phbender for reporting back and closing the issue :+1:

Was this page helpful?
0 / 5 - 0 ratings