Search code examples
pythonmongodbflaskmongoengineflask-mongoengine

How to close db with flask_mongoengine?


I am learning to use flask and flask_mongoengine to create a website. Follow the flask tutorial 1.0.2 version. But I ran into a problem, how to implement the get_db() and close_db() function?

Currently, what I am doing is :

myapp.py

....
def create_app():
    app = Flask(__name__)

    from db import db
    db.init_app(app)

    @app.route('/')
    def home():
        ...

    return app

db.py

from flask import g
from flask_mongoengine import MongoEngine

db = MongoEngine()

def get_db():
    g.db = ???
    return g.db

def close_db():
    db = g.pop('db', None)

    if db is not None:
        ??? # db.close() doesn't exist!!!

I am very confused about how to do this part. Can someone give any suggestions? In flask_mongoengine tutorial page, they don't implement the get_db() and close_db() ...


Solution

  • Confusion happens because in those tutorials there are too many programming patterns. In flask-1.0.2 tutorial they use getter method pattern and but flask-mongoengine relies on bootstraping a db to flask-app-instance, which relies on a builder pattern — Flask Application Factories. It may still be confusing but I'll show you how it's meant to be done.

    Bootstrap a flask-mongoengine in create_app:

    def create_app(test_config=None):
        app = Flask(__name__)
        # configure mongo settings here like in flask-mongoengine docs
    
        g.db = db = MongoEngine()
        db.init_app(app)
    
    def get_db():
        return g.db
    
    def close_db():
        pass
    

    What's about close_db()? Well, that function exists in case db you've chosen needs some cleanup actions to be closed. But I haven't found in mongoengine docs any explicit mention that mongoengine db connection need a cleanup actions from you to be closed, so you can just pass it.