Skip to content
Myr

Added MongoKit pattern and fixed typo in sqlalchemy pattern

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Christopher Grebs · committed by Armin Ronacher · parent 67f3f1b · Browse files · 1 file+133 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+133 added−0 removed

  • other:+133 added−0 removed

1 file+133 added−0 removed

added:docs/patterns/mongokit.rst+133 added
1.. mongokit-pattern:23MongoKit in Flask4=================56Using a document database rather than a full DBMS gets more common these days.7This pattern shows how to use MongoKit, a document mapper library, to8integrate with MongoDB.910This pattern requires an running MongoDB server and the MongoKit library11installed.1213There are two very common ways to use MongoKit. I will outline each of them14here:151617Declarative18-----------1920The default behaviour of MongoKit is the declarative one that is based on21common ideas from Django or the SQLAlchemy declarative extension.2223Here an example `database.py` module for your application::2425 from mongokit import Connection, Document2627 connection = Connection()282930To define your models, just subclass the `Document` class that is imported31from MongoKit. If you've seen the SQLAlchemy pattern you may wonder why we do32not have a session and even do not define a `init_db` function here. On the33one hand, MongoKit does not have something like a session. This sometimes34makes it more to type but also makes it blazingly fast. On the other hand,35MongoDB is schemaless. This means you can modify the data structure from one36insert query to the next without any problem. MongoKit is just schemaless37too, but implements some validation to ensure data integrity.3839Here is an example document (put this into `models.py`, e.g.)::4041 from yourapplication.database import Document, connection42 43 def max_length(length):44 def validate(value):45 if len(value) <= length:46 return True47 raise Exception('%s must be at most %s characters long' % length)48 return validate4950 class User(Document):51 structure = {52 'name': unicode,53 'email': unicode,54 }55 validators = {56 'name': max_length(50),57 'email': max_length(120)58 }59 use_dot_notation = True60 def __repr__(self):61 return '<User %r>' % (self.name)6263 # register the User document with our current connection64 connection.register([User])656667This example shows you how to define your schema (named structure), a68validator for the maximum character length and uses a special MongoKit feature69called `use_dot_notation`. Per default MongoKit behaves like a python70dictionary but with `use_dot_notation` set to `True` you can use your71documents like you use models in nearly any other ORM by using dots to72seperate between attributes.7374You can insert entries into the database like this:7576>>> from yourapplication.database import connection77>>> from yourapplication.models import User78>>> collection = connection['test'].users79>>> user = collection.User()80>>> user['name'] = u'admin'81>>> user['email'] = u'admin@localhost'82>>> user.save()8384Note that MongoKit is kinda strict with used column types, you must not use a85common `str` type for either `name` or `email` but unicode.8687Querying is simple as well:8889>>> list(collection.User.find())90[<User u'admin'>]91>>> collection.User.find_one({'name': u'admin'})92<User u'admin'>9394.. _MongoKit: http://bytebucket.org/namlook/mongokit/959697PyMongo Compatibility Layer98---------------------------99100If you just want to use PyMongo, you can do that with MongoKit as well. You101may use this process if you need the best performance to get::102103 from MongoKit import Connection104105 connection = Connection()106107To insert data you can use the `insert` method. We have to get a108collection first, this is somewhat the same as a table in the SQL world.109110>>> collection = connection['test'].users111>>> user = {'name': u'admin', 'email': u'admin@localhost'}112>>> collection.insert(user)113114print list(collection.find())115print collection.find_one({'name': u'admin'})116117MongoKit will automatically commit for us.118119To query your database, you use the collection directly:120121>>> list(collection.find())122[{u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'}]123>>> collection.find_one({'name': u'admin'})124{u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'}125126These results are also dict-like objects:127128>>> r = collection.find_one({'name': u'admin'})129>>> r['email']130u'admin@localhost'131132For more information about MongoKit, head over to the133`website <http://bytebucket.org/namlook/mongokit/>`_.