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
Provenance
- Commit
824c10c- Tree
e629f2b- Author
Christopher Grebs <cg@webshox.org>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
67f3f1b
1 file changed+133 added−0 removed
added:docs/patterns/mongokit.rst+133 added
1+.. mongokit-pattern:2+3+MongoKit in Flask4+=================5+6+Using a document database rather than a full DBMS gets more common these days.7+This pattern shows how to use MongoKit, a document mapper library, to8+integrate with MongoDB.9+10+This pattern requires an running MongoDB server and the MongoKit library11+installed.12+13+There are two very common ways to use MongoKit. I will outline each of them14+here:15+16+17+Declarative18+-----------19+20+The default behaviour of MongoKit is the declarative one that is based on21+common ideas from Django or the SQLAlchemy declarative extension.22+23+Here an example `database.py` module for your application::24+25+ from mongokit import Connection, Document26+27+ connection = Connection()28+29+30+To define your models, just subclass the `Document` class that is imported31+from MongoKit. If you've seen the SQLAlchemy pattern you may wonder why we do32+not have a session and even do not define a `init_db` function here. On the33+one hand, MongoKit does not have something like a session. This sometimes34+makes it more to type but also makes it blazingly fast. On the other hand,35+MongoDB is schemaless. This means you can modify the data structure from one36+insert query to the next without any problem. MongoKit is just schemaless37+too, but implements some validation to ensure data integrity.38+39+Here is an example document (put this into `models.py`, e.g.)::40+41+ 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 validate49+50+ 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)62+63+ # register the User document with our current connection64+ connection.register([User])65+66+67+This example shows you how to define your schema (named structure), a68+validator for the maximum character length and uses a special MongoKit feature69+called `use_dot_notation`. Per default MongoKit behaves like a python70+dictionary but with `use_dot_notation` set to `True` you can use your71+documents like you use models in nearly any other ORM by using dots to72+seperate between attributes.73+74+You can insert entries into the database like this:75+76+>>> 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()83+84+Note that MongoKit is kinda strict with used column types, you must not use a85+common `str` type for either `name` or `email` but unicode.86+87+Querying is simple as well:88+89+>>> list(collection.User.find())90+[<User u'admin'>]91+>>> collection.User.find_one({'name': u'admin'})92+<User u'admin'>93+94+.. _MongoKit: http://bytebucket.org/namlook/mongokit/95+96+97+PyMongo Compatibility Layer98+---------------------------99+100+If you just want to use PyMongo, you can do that with MongoKit as well. You101+may use this process if you need the best performance to get::102+103+ from MongoKit import Connection104+105+ connection = Connection()106+107+To insert data you can use the `insert` method. We have to get a108+collection first, this is somewhat the same as a table in the SQL world.109+110+>>> collection = connection['test'].users111+>>> user = {'name': u'admin', 'email': u'admin@localhost'}112+>>> collection.insert(user)113+114+print list(collection.find())115+print collection.find_one({'name': u'admin'})116+117+MongoKit will automatically commit for us.118+119+To query your database, you use the collection directly:120+121+>>> 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'}125+126+These results are also dict-like objects:127+128+>>> r = collection.find_one({'name': u'admin'})129+>>> r['email']130+u'admin@localhost'131+132+For more information about MongoKit, head over to the133+`website <http://bytebucket.org/namlook/mongokit/>`_.