I use FastAPI in a microservice environment on a public cloud. Most of the request needs a pymongo and redis connection. The preferred model of FastAPI is to inject db connections via dependencies. However the DB is rolling its credentials once a month. For a new DB connection I retrieve the secret from the secret store (https request) and initiate the connection. This process is quite heavy if you do this at every request. Thus, I would init the client and pass it as variable to the dependencies. But if the credentials change, this would lead to an error.
Can I do something like this in FastAPI (I did in Flask):
try:
crud_to_db()
except ConnectionError:
re_init_db_connection_on_app_level()
crud_to_db()