Ulrich Schuster
Ulrich Schuster

Reputation: 1916

Flask-Mongoengine always connects to `test` database

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?

Upvotes: 1

Views: 1107

Answers (2)

Harish Salluri
Harish Salluri

Reputation: 1

I have faced the same problem. When you get the connection string from Azure portal, it looks like this.

export MONGODBCONNSTR="mongodb://<USERNAME>:<PASSWORD>@<HOST>:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@cpe-self-service-db@"  

Adding my database name 'MYDB' to this connection in the URI as below.

export MONGODBCONNSTR="mongodb://<USERNAME>:<PASSWORD>@<HOST>:10255/MYDB?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@cpe-self-service-db@" 

Then I have update from

 app.config['MONGODB_SETTINGS'] = {
    'host': f'{os.environ.get("MONGODBCONNSTR")}/MYDB'
}

TO

app.config['MONGODB_SETTINGS'] = {  
        'host': f'{os.environ.get("MONGODBCONNSTR")}'  
    }  

OR

app.config['MONGODB_HOST'] = f'{os.environ.get("MONGODBCONNSTR")}'

It worked for me.

Upvotes: 0

Mathieu Dhondt
Mathieu Dhondt

Reputation: 8934

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.

Upvotes: 2

Related Questions