0

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()
Lau
  • 1,353
  • 7
  • 26
  • Any reason why it wouldn't work? You should be able to have that check inside the function you've added in a `Depends`, which would then reestablish the connection for the global connection pool? – MatsLindh Jun 30 '21 at 12:19
  • Have you considered caching the credentials for a short period of time? 1 hour or so? – AndreFeijo Jun 30 '21 at 21:25

0 Answers0