Giannis
Giannis

Reputation: 5526

MongoEngine change database

Due to my project setup (same as flasky) , when I run my python tests (line 34), a connection to the development database is created, before my configuration is set to test (line 11 here). This results in problems with my tests, since they are meant to run on a clean DB.

Looking online, I only found descriptions of switch_db but this is not what I need. I need to either change the database my connection is using, or drop the connection and create a new one. I cant find a way to do either of these.. Am I missing something ? My connection is simply initialized using this line of code, inside init.py of my main app directory.

from mongoengine import connection
db_name = 'name_from_config'
connection(db_name)

Upvotes: 2

Views: 1536

Answers (2)

blackjack
blackjack

Reputation: 101

Something like this in mongoengine

from flask.ext.mongoengine import mongoengine
mongoengine.register_connection("alias1", "db1")
mongoengine.register_connection("alias2", "db2")

and in model, add in entry in meta or use switch method of queryset

similar question at stackoverflow

Upvotes: 1

Steve Rossiter
Steve Rossiter

Reputation: 2925

You should avoid creating the connection to mongoengine in the way you describe for precisely this reason. Flasky is using an application factory approach which allows the application to know which connection config to use when implementing the data models.

The best way to integrate mongoenigne into your app is with something like flask-mongoengine which will should solve this problem out-of-the-box.

Upvotes: 0

Related Questions