I am using flask together with flask-mongoengine. The application is set up via an application factory as described here.
My models are defined in separate files, as follows:
from flask_mongoengine import MongoEngine
db = MongoEngine()
class NodeModel(db.Document):
node_id = db.UUIDField(primary_key=True)
....
The application factory in __init__.py
looks as follows:
def create_app():
app = Flask(__name__, static_url_path=''
...
app.config['MONGODB_DB'] = 'myDb'
app.config['MONGODB_HOST'] = ....
app.config['MONGODB_UUIDREPRESENTATION'] = 'standard'
with app.app_context():
from models import db
db.init_app(app)
...
return app
The application fires up correctly, all routes are working. However, data is stored in the default test
database, not in myDb
. Other MongoDB configurations, like the host and MONGODB_UUIDREPRESENTATION
are respected. I have been researching this problem for several hours now, but to no avail. What am I missing? How do I set up flask-mongoengine to connect with the correct database?
Does it help if you do it through app.config['MONGODB_SETTINGS']
?
e.g.
app.config['MONGODB_SETTINGS'] = {
'db': 'myDb',
'host': os.getenv('MONGODB_HOST', 'localhost:27017'),
}
Also, mind that database name from uri has priority over name. So if you use
app.config['MONGODB_SETTINGS'] = {
'db': 'myDb',
'host': 'mongodb://localhost/',
...
}
mongoengine will write to the test
db, because there's none set in host.
By the way, I think mongoengine doesn't always pick up on db name in the URI, because when I recently used this
app.config['MONGODB_SETTINGS'] = {
'host': 'mongodb://localhost/myDb',
...
}
mongoengine kept writing to test
as well.