Flask-MongoObject is an extension for Flask that adds support for MongoDB in your application. It’s based on the excellent pymongo library and add a few more features such as retrieving objects, auto-refenrence and dereference objects. The extensions is based on minimongo but has been adapted to Flask and added/removed a few features on its own.
For most cases, all you have to do is create your Flask application, loading your configuration and then create MongoObject object by passing the application to it
Once create, that object will contain all the functions and helpers you need to access your MongoDB database. It also provides a Model that can be used to declare your Model object:
from flask import Flask
from flaskext.mongoobject import MongoObject
app = Flask(__name__)
app.config['MONGODB_HOST'] = "mongodb://localhost:27017"
app.config['DEBUG'] = True
app.config['MONGODB_DATABASE'] = "hello"
db = MongoObject(app)
class Post(db.Model):
__collection__ = "posts"
Make sure that your MongoDB database is running. To create a new post:
>>> from yourapplication import Post
>>> first = Post(title="test", content="hello")
>>> second = Post({"title": "hello", "content": "second post"})
As you have notice, Model can accept both kwargs as well as a dictionary to populate the model information. The created models have not been saved into database yet. To save them, simply call:
>>> first.save()
>>> second.save()
Then, when you want to access the saved objects:
>>> User.query.find({"title": "test"})
The Model has a query attribute similar to Flask-SQLAlchemy that can be used to query the collections. In fact, it’s only a very thin layer to pymongo.Collection
A list of configuration keys of the extensions
MONGODB_HOST | accept a full mongodb uri for the connection. Examples: “mongodbL//localhost:27017” |
MONGODB_DATABASE | database that we are going to connect to |