Flask-MongoKit

Flask-MongoKit simplifies to use MongoKit, a powerful MongoDB ORM in Flask applications. If you find bugs or want to support this extension you can find the source code here.

Installation

The installation is thanks to the Python Package Index and pip really simple.

$ pip install Flask-MongoKit

If you only can use easy_install than use

$ easy_install Flask-MongoKit

Flask-MongoKit requires to run some packages (they will be installed automatically if they not already installed):

  • Flask
  • MongoKit
  • pymongo

Your first Document

It is very simple to use MongoKit in your Flask application. Let’s create a simple ToDo application.

from datetime import datetime

from flask import Flask, request, render_template, redirect, url_for
from flask.ext.mongokit import MongoKit, Document

app = Flask(__name__)

class Task(Document):
    __collection__ = 'tasks'
    structure = {
        'title': unicode,
        'text': unicode,
        'creation': datetime,
    }
    required_fields = ['title', 'creation']
    default_values = {'creation': datetime.utcnow}
    use_dot_notation = True

db = MongoKit(app)
db.register([Task])

As you can see we create a document model as class Task which uses Document from flask.ext.mongokit as parent class. In this model we describe the structure of our document and we can set a list of required fields and default values. The flask.ext.mongokit.Document is beside some extensions the same like mongokit.Document so if you want to know more about the core features of the Document class please look into the MongoKit documentation. For using the the document model we must register it with the connection. But we use the register() method from the flask.ext.mongokit.MongoKit class.

Now we need a view to add a new task like this.

@app.route('/new', methods=["GET", "POST"])
def new_task():
    if request.method == 'POST':
        task = db.Task()
        task.title = request.form['title']
        task.text = request.form['text']
        task.save()
        return redirect(url_for('show_all'))
    return render_template('new.html')

If someone now clicks on the submit button of the form your application will create a new instance of your Task model class. After that we set title and text of the task and save it into your MongoDB.

But now we want to get a list of task, so we add an other view.

@app.route('/')
def show_all():
    tasks = db.Task.find()
    return render_template('list.html', tasks=tasks)

This view is very simple. You can see we only call the find() method and put the result into our template. Now we have a running example that works simple with a MongoDB inside a Flask application.

If you want to see a full example of Flask-MongoKit look inside the repository. You will find there this ToDo application with the matching templates.

Configuration values

The following configuration variables are used in Flask-MongoKit:

MONGODB_DATABASE

The database name that should used.

Default value: flask

MONGODB_HOST

Hostname or IP address of the MongoDB host.

Default value: localhost

MONGODB_PORT

Listening port of the MongoDB host.

Default value: 27017

MONGODB_USERNAME

If you need authentication than you can set there your username.

Default value: None

MONGODB_PASSWORD

Password for authentication.

Default value: None

Request and App context

If you want to make some operations on your MongoDB with Flask-MongoKit you need a context like the request or app context. If you want to use it for example in Flask-Script than the best choise is the app context (implemented since Flask v0.9). There is a small example how to use the app context.:

from flask import Flask
from flask.ext.mongokit import MongoKit

app = Flask(__name__)
db = MongoKit(app)

with app.app_context():
    db['my_collection'].insert({'x': 5})
    print db['my_collection'].find_one({'x': 5})

You can also use it in the normal request context like insite of a view function or in the test request context like the following example.:

with app.test_request_context('/'):
    db['my_collection'].insert({'x': 5})
    print db['my_collection'].find_one({'x': 5})

Changelog

  • 0.6 (08.07.2012)

    • Use the new app context and again the old request context, see Request and App context.

    • The MongoKit object is now subscriptable and support the typical syntax to get a collection.:

      db['my_collection'].insert({'x': 5})
      
    • Restructured and improved test suite.

    • Sounds crazy but improved python2.5 support.

  • 0.5 (02.07.2012)

    • You don’t need a request context anymore for the mongodb connection. (A bad decision ... look in 0.6)
  • 0.4 (23.02.2012)

    • Support new import system of flask. Use now:

      form flask.ext.mongokit import Mongokit

API Documentation

class flask_mongokit.MongoKit(app=None)

This class is used to integrate MongoKit into a Flask application.

Parameters:app – The Flask application will be bound to this MongoKit instance. If an app is not provided at initialization time than it must be provided later by calling init_app() manually.
connect()

Connect to the MongoDB server and register the documents from registered_documents. If you set MONGODB_USERNAME and MONGODB_PASSWORD then you will be authenticated at the MONGODB_DATABASE.

connected

Connection status to your MongoDB.

disconnect()

Close the connection to your MongoDB.

init_app(app)

This method connect your app with this extension. Flask- MongoKit will now take care about to open and close the connection to your MongoDB.

Also it registers the flask.ext.mongokit.BSONObjectIdConverter as a converter with the key word ObjectId.

Parameters:app – The Flask application will be bound to this MongoKit instance.
register(documents)

Register one or more mongokit.Document instances to the connection.

Can be also used as a decorator on documents:

db = MongoKit(app)

@db.register
class Task(Document):
    structure = {
       'title': unicode,
       'text': unicode,
       'creation': datetime,
    }
Parameters:documents – A list of mongokit.Document.
registered_documents = None

list of mongokit.Document which will be automated registed at connection

class flask_mongokit.Document(doc=None, gen_skel=True, collection=None, lang='en', fallback_lang='en')
find_one_or_404(*args, **kwargs)

This method get one document over normal query parameter like find_one() but if there no document then it will raise a 404 error.

get_or_404(id)

This method get one document over the _id field. If there no document with this id then it will raised a 404 error.

Parameters:id – The id from the document. The most time there will be an bson.objectid.ObjectId.
class flask_mongokit.BSONObjectIdConverter(map)

A simple converter for the RESTfull URL routing system of Flask.

@app.route('/<ObjectId:task_id>')
def show_task(task_id):
    task = db.Task.get_from_id(task_id)
    return render_template('task.html', task=task)

It checks the validate of the id and converts it into a bson.objectid.ObjectId object. The converter will be automatically registered by the initialization of MongoKit with keyword ObjectId.

Fork me on GitHub