Flask Mongoengine, Multiple Databases With Alias

January 11, 2019
Flask MongoEngine Python

It’s common in some occasions our applications are consuming and storing data from two or more MongoDB databases, and if you are using Mongoengine as your database abstraction you are lucky enough that Mongoengine is capable to accessing multiple database without hassle, refering this documentation: http://docs.mongoengine.org/guide/connecting.html?highlight=alias#multiple-databases, we can connecting to multiple database and using alias or db_alias

Now, for accessing multiple database with Flask and Flask-Mongoengine, first define the database connection info and credentials in our flask config file config.py

from pymongo.read_preferences import ReadPreference

MONGO_DB_MARS_ALIAS = 'mars'
MONGO_DB_EARTH_ALIAS = 'earth'

MONGODB_SETTINGS = [
    {
        'ALIAS': MONGO_DB_MARS_ALIAS,
        'DB': MONGO_DB_MARS_ALIAS,
        'USERNAME': MONGO_DB_MARS_ALIAS,
        'PASSWORD': 'password_mars',
        'HOST': 'private-db.mars.net',
        'PORT': 27017,
        'REPLICASET': 'MainRepSet',
    },
    {
        'ALIAS': MONGO_DB_EARTH_ALIAS,
        'DB': MONGO_DB_EARTH_ALIAS,
        'USERNAME': 'MONGO_DB_EARTH_ALIAS',
        'PASSWORD': 'password_earth',
        'HOST': 'private-db.earth.net',
        'PORT': 27017,
    }
]

Set mongo instance in flask __init__.py file

# ... app is already defined before 

from flask_mongoengine import MongoEngine 

MongoDB = MongoEngine()
MongoDB.init_app(app)

Then define our model class and set alias in meta field with db_alias

from datetime import datetime
from app import MongoDB
from config import MONGO_DB_MARS_ALIAS, MONGO_DB_EARTH_ALIAS

class MarsActivityLogs(MongoDB.DynamicDocument):
    module = MongoDB.StringField(default='')
    tags = MongoDB.ListField(MongoDB.StringField(), default=[])
    data_dict = MongoDB.DictField(default={})

    created_at = MongoDB.DateTimeField(default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    updated_at = MongoDB.DateTimeField(default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

    meta = {
        'db_alias': MONGO_DB_MARS_ALIAS, ## set database alias, this is the most important thing
        'collection': 'activity_logs' ## this is the collection name from your database alias
    }

class EarthActivityLogs(MongoDB.DynamicDocument):
    module = MongoDB.StringField(default='')
    tags = MongoDB.ListField(MongoDB.StringField(), default=[])
    data_dict = MongoDB.DictField(default={})

    created_at = MongoDB.DateTimeField(default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    updated_at = MongoDB.DateTimeField(default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

    meta = {
        'db_alias': MONGO_DB_EARTH_ALIAS,
        'collection': 'activity_logs'
    }

Thats all, from now if you query with MarsActivityLogs then you are accessing 1st mongodb server and vice-versa.

comments powered by Disqus