Checking database connection with flask_mongoengine

262 Views Asked by At

I am practicing python with flask, flask_mongoengine and mongoDB. I have followed various tutorials and for the moment am using application factory to set up my App (webservice for querying a database). Code looks something like this:

db = MongoEngine()

def initialise_db(app):
    db.init_app(app)

def create_app():
    app = Flask(__name__)
    api = Api(app)
    initialise_db(app)
    initialise_routes(api)
    return app

I'd like to know if there is a way of checking the database connection is OK, before creating the app. Here the initialise_db(app) runs with no error even if there is no running instance of mongoDB (on port 21017 or other if specified in app.config). I only get an error at the point were I try to do a db.Document.save()...


EDIT:

I have implemented a simple check_connection() function where I try to save a generic document in my DB, and raise an exception if this fails:

from db_models import checkElement

def check_connection():
    try:
        checkElement(checkID=1).save()
        saved = True
    except Exception as e:
        saved = False
        raise e
    finally:
        if saved:
            checkElement.objects.get(checkID=1).delete()

I'm pretty sure this is not a very clean way to check for a DB connection, is there a better way to do the same with mongoengine/pymongo ??

0

There are 0 best solutions below