¡Esta es una revisión vieja del documento!
pip install Flask-MongoAlchemy
from flask import Flask from flask.ext.mongoalchemy import MongoAlchemy app = Flask(__name__) app.config['MONGOALCHEMY_DATABASE'] = 'library' db = MongoAlchemy(app) class Author(db.Document): name = db.StringField() class Book(db.Document): title = db.StringField() author = db.DocumentField(Author) year = db.IntField()
There are other ways to initialize it:
app = Flask(__name__) db = MongoAlchemy(app)
db = MongoAlchemy() def init_app(): app = Flask(__name__) db.init_app(app) return app
Now you can create authors and books:
>>> from application import Author, Book >>> mark_pilgrim = Author(name='Mark Pilgrim') >>> dive = Book(title='Dive Into Python', author=mark_pilgrim, year=2004) >>> mark_pilgrim.save() >>> dive.save()
If you make any changes on a document, you may call save() again:
>>> mark_pilgrim.name = 'Mark Stalone' >>> mark_pilgrim.save()
And you can remove a document from the database by calling its remove() method:
>>> dive.remove()
Every document has a query class property. It’s very simple to use it:
>>> mark = Author.query.get('76726') >>> mark.name = 'Mark Pilgrim' >>> mark.save()
You also can use the filter method instead of the get() method:
>>> mark = Author.query.filter(Author.name == 'Mark Pilgrim').first() >>> mark.name = 'Steve Jobs' >>> mark.save()
>>> app.config['MONGOALCHEMY_SERVER_AUTH'] = False
There are values to change in Mongo config:
When MongoAlchemy or init_app() are invoked with only one argument (the Flask instance), a configuration value prefix of MONGOALCHEMY is assumed; this can be overridden with the config_prefix argument, for example:
app = Flask(__name__) # defaulting to MONGOENGINE prefix mongo1 = MongoAlchemy(app) # using another database config app.config['OTHER_DBNAME'] = 'other' mongo2 = MongoAlchemy(app, config_prefix='OTHER')