0

I've got a simple FastAPI webapp going and I'd like to be able to check the database connection on startup (and retry connection if it fails)

I've got the following code, but it doesn't feel right

# main.py
import uvicorn

from backend.app import app


if __name__ == "__main__":
    uvicorn.run(app, port=8001)
# app.py
# ... omitted for brevity
from backend.database import notes, tags
# ... omitted for brevity
# database.py
from motor.motor_asyncio import AsyncIOMotorClient
from asyncio import get_event_loop


client = AsyncIOMotorClient("localhost", 27027)

loop = get_event_loop()
data = loop.run_until_complete(client.server_info())
db = client.notes_db

notes = db.notes
tags = db.tags

Without get_event_loop() and the subsequent loop.run_until_complete() call it won't test the database connection until you actually try to access / write to it.

My goal is to be able to halt the startup process until it can successfully connect to a database, is there any clean way to do this with Python and motor.io (https://motor.readthedocs.io/, sorry there's no tag for it) ?

Enrico Tuvera Jr
  • 2,739
  • 6
  • 35
  • 51

1 Answers1

1

the startup event in FastAPI is the deal here I guess. I addition this repository is a nice example and this thread could even provide you with more information. You could execute your tests within the startup event. This means the application won't start until the startup event has been successfully executed.

mustafasencer
  • 723
  • 4
  • 12