Skip to content
Myr

mongokit.rst

This file

Path

docs/patterns/mongokit.rst

143 lines · 4.7 KiB

Last changed by

Merge pull request #1280 from jcomo/mongokit-doc-updateMarkus Unterwaditzerbefore adoptionb7dfa6c

History of this file

Take it

The walk stopped after 200 commits: lines older than 5693b9d point at it.

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 1–22why, one step back
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 a 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 behavior of MongoKit is the declarative one that is based on21common ideas from Django or the SQLAlchemy declarative extension.22

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 23why, one step back
23Here an example :file:`app.py` module for your application::

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 24–49why, one step back
24
25 from flask import Flask26 from mongokit import Connection, Document2728 # configuration29 MONGODB_HOST = 'localhost'30 MONGODB_PORT = 270173132 # create the little application object33 app = Flask(__name__)34 app.config.from_object(__name__)3536 # connect to the database37 connection = Connection(app.config['MONGODB_HOST'],38 app.config['MONGODB_PORT'])394041To define your models, just subclass the `Document` class that is imported42from MongoKit. If you've seen the SQLAlchemy pattern you may wonder why we do43not have a session and even do not define a `init_db` function here. On the44one hand, MongoKit does not have something like a session. This sometimes45makes it more to type but also makes it blazingly fast. On the other hand,46MongoDB is schemaless. This means you can modify the data structure from one47insert query to the next without any problem. MongoKit is just schemaless48too, but implements some validation to ensure data integrity.49

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 50why, one step back
50Here is an example document (put this also into :file:`app.py`, e.g.)::

Merge pull request #1280 from jcomo/mongokit-doc-updateMarkus Unterwaditzerbefore adoptionb7dfa6c

line 51why, one step back
51 from mongokit import ValidationError

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 52–56why, one step back
52
53 def max_length(length):54 def validate(value):55 if len(value) <= length:56 return True

Merge pull request #1280 from jcomo/mongokit-doc-updateMarkus Unterwaditzerbefore adoptionb7dfa6c

lines 57–58why, one step back
57 # must have %s in error format string to have mongokit place key in there
58 raise ValidationError('%s must be at most {} characters long'.format(length))

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 59–80why, one step back
59 return validate
6061 class User(Document):62 structure = {63 'name': unicode,64 'email': unicode,65 }66 validators = {67 'name': max_length(50),68 'email': max_length(120)69 }70 use_dot_notation = True71 def __repr__(self):72 return '<User %r>' % (self.name)7374 # register the User document with our current connection75 connection.register([User])767778This example shows you how to define your schema (named structure), a79validator for the maximum character length and uses a special MongoKit feature80called `use_dot_notation`. Per default MongoKit behaves like a python

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 81why, one step back
81dictionary but with `use_dot_notation` set to ``True`` you can use your

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 82–143why, one step back
82documents like you use models in nearly any other ORM by using dots to
83separate between attributes.8485You can insert entries into the database like this:8687>>> from yourapplication.database import connection88>>> from yourapplication.models import User89>>> collection = connection['test'].users90>>> user = collection.User()91>>> user['name'] = u'admin'92>>> user['email'] = u'admin@localhost'93>>> user.save()9495Note that MongoKit is kinda strict with used column types, you must not use a96common `str` type for either `name` or `email` but unicode.9798Querying is simple as well:99100>>> list(collection.User.find())101[<User u'admin'>]102>>> collection.User.find_one({'name': u'admin'})103<User u'admin'>104105.. _MongoKit: http://bytebucket.org/namlook/mongokit/106107108PyMongo Compatibility Layer109---------------------------110111If you just want to use PyMongo, you can do that with MongoKit as well. You112may use this process if you need the best performance to get. Note that this113example does not show how to couple it with Flask, see the above MongoKit code114for examples::115116 from MongoKit import Connection117118 connection = Connection()119120To insert data you can use the `insert` method. We have to get a121collection first, this is somewhat the same as a table in the SQL world.122123>>> collection = connection['test'].users124>>> user = {'name': u'admin', 'email': u'admin@localhost'}125>>> collection.insert(user)126127MongoKit will automatically commit for us.128129To query your database, you use the collection directly:130131>>> list(collection.find())132[{u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'}]133>>> collection.find_one({'name': u'admin'})134{u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'}135136These results are also dict-like objects:137138>>> r = collection.find_one({'name': u'admin'})139>>> r['email']140u'admin@localhost'141142For more information about MongoKit, head over to the143`website <https://github.com/namlook/mongokit>`_.