Rolando
Rolando

Reputation: 62626

How to dbchange mongo flask?

I have a flask based application that I am configuring like:

from flask import Flask
from flask.ext.mongoengine import MongoEngine

app = Flask(__name__)
app.config["MONGODB_DB"] = "my_tumble_log"
app.config["SECRET_KEY"] = "KeepThisS3cr3t"

db = MongoEngine(app)

if __name__ == '__main__':
    app.run()

I have a models.py file that contains all my models kind of like: import datetime

from flask import url_for
from tumblelog import db


class Post(db.Document):
    created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
    title = db.StringField(max_length=255, required=True)
    slug = db.StringField(max_length=255, required=True)
    body = db.StringField(required=True)
    comments = db.ListField(db.EmbeddedDocumentField('Comment'))

    def get_absolute_url(self):
        return url_for('post', kwargs={"slug": self.slug})

    def __unicode__(self):
        return self.title

    meta = {
        'allow_inheritance': True,
        'indexes': ['-created_at', 'slug'],
        'ordering': ['-created_at']
    }

I want to define a new route such that I can use another database and its collections there:

@app.route('/sampleroute')
def sample_route():
    #Insert Code to use another database of a specific name
    #Query Out a particular "OtherClass" that would be in models.py

What do I need to do to be able to set "db" equal to some other database like "db1" instead of "my_tumble_log" for just within that "/sampleroute"? Can I declare "OtherClass" within its own class like Post does in the same models.py file? Or is what I want to do not doable with MongoEngine?

Upvotes: 1

Views: 900

Answers (3)

I did my work like this: 1,in my models.py:

meta = {'db_alias': 'user-db'}

2,in my app/init.py:

from flask.ext.mongoengine import MongoEngine
db = MongoEngine()
db.register_connection('user-db', name='user-db')

3,That's work.

Upvotes: 0

EricSRK
EricSRK

Reputation: 145

just use {"db_alias": alias_name} in your Document class

just to make sure you register the alias name register_connect(alias_name,db,host,port) you can register as many alias as you want. here is the doc for register_connect: https://mongoengine-odm.readthedocs.org/en/latest/apireference.html#mongoengine.register_connection

Upvotes: 0

Gianfranco P
Gianfranco P

Reputation: 10794

To use multiple databases you can use connect() and provide an alias name for the connection.

Then, in the model.py add a meta tag to specify the database:

meta = {"db_alias": "user-db"}

See Connecting to MongoDB in the doc for more info

Upvotes: 2

Related Questions