Skip to content
Myr

mongokit.rst

This file

Path

docs/patterns/mongokit.rst

144 lines · 4.6 KiB

Last changed by

fixed mongokit pattern to show how the flask way to configure hostname and portChristopher Grebsbefore adoption87c2c79

History of this file

Take it

Added MongoKit pattern and fixed typo in sqlalchemy patternChristopher Grebsbefore adoption824c10c

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 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.22

fixed mongokit pattern to show how the flask way to configure hostname and portChristopher Grebsbefore adoption87c2c79

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

Added MongoKit pattern and fixed typo in sqlalchemy patternChristopher Grebsbefore adoption824c10c

line 24why, one step back
24

fixed mongokit pattern to show how the flask way to configure hostname and portChristopher Grebsbefore adoption87c2c79

line 25why, one step back
25 from flask import Flask

Added MongoKit pattern and fixed typo in sqlalchemy patternChristopher Grebsbefore adoption824c10c

lines 26–27why, one step back
26 from mongokit import Connection, Document
27

fixed mongokit pattern to show how the flask way to configure hostname and portChristopher Grebsbefore adoption87c2c79

lines 28–30why, one step back
28 # configuration
29 MONGODB_HOST = 'localhost'30 MONGODB_PORT = 27017

Added MongoKit pattern and fixed typo in sqlalchemy patternChristopher Grebsbefore adoption824c10c

line 31why, one step back
31

fixed mongokit pattern to show how the flask way to configure hostname and portChristopher Grebsbefore adoption87c2c79

lines 32–34why, one step back
32 # create the little application object
33 app = Flask(__name__)34 app.config.from_object(__name__)

Added MongoKit pattern and fixed typo in sqlalchemy patternChristopher Grebsbefore adoption824c10c

line 35why, one step back
35

fixed mongokit pattern to show how the flask way to configure hostname and portChristopher Grebsbefore adoption87c2c79

lines 36–40why, one step back
36 # connect to the database
37 connection = Connection(app.config['MONGODB_HOST'],38 app.config['MONGODB_PORT'])3940

Added MongoKit pattern and fixed typo in sqlalchemy patternChristopher Grebsbefore adoption824c10c

lines 41–49why, one step back
41To define your models, just subclass the `Document` class that is imported
42from 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

fixed mongokit pattern to show how the flask way to configure hostname and portChristopher Grebsbefore adoption87c2c79

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

Added MongoKit pattern and fixed typo in sqlalchemy patternChristopher Grebsbefore adoption824c10c

lines 51–109why, one step back
51
52 def max_length(length):53 def validate(value):54 if len(value) <= length:55 return True56 raise Exception('%s must be at most %s characters long' % length)57 return validate5859 class User(Document):60 structure = {61 'name': unicode,62 'email': unicode,63 }64 validators = {65 'name': max_length(50),66 'email': max_length(120)67 }68 use_dot_notation = True69 def __repr__(self):70 return '<User %r>' % (self.name)7172 # register the User document with our current connection73 connection.register([User])747576This example shows you how to define your schema (named structure), a77validator for the maximum character length and uses a special MongoKit feature78called `use_dot_notation`. Per default MongoKit behaves like a python79dictionary but with `use_dot_notation` set to `True` you can use your80documents like you use models in nearly any other ORM by using dots to81seperate between attributes.8283You can insert entries into the database like this:8485>>> from yourapplication.database import connection86>>> from yourapplication.models import User87>>> collection = connection['test'].users88>>> user = collection.User()89>>> user['name'] = u'admin'90>>> user['email'] = u'admin@localhost'91>>> user.save()9293Note that MongoKit is kinda strict with used column types, you must not use a94common `str` type for either `name` or `email` but unicode.9596Querying is simple as well:9798>>> list(collection.User.find())99[<User u'admin'>]100>>> collection.User.find_one({'name': u'admin'})101<User u'admin'>102103.. _MongoKit: http://bytebucket.org/namlook/mongokit/104105106PyMongo Compatibility Layer107---------------------------108109If you just want to use PyMongo, you can do that with MongoKit as well. You

fixed mongokit pattern to show how the flask way to configure hostname and portChristopher Grebsbefore adoption87c2c79

lines 110–112why, one step back
110may use this process if you need the best performance to get. Note that this
111example does not show how to couple it with Flask, see the above MongoKit code112for examples::

Added MongoKit pattern and fixed typo in sqlalchemy patternChristopher Grebsbefore adoption824c10c

lines 113–144why, one step back
113
114 from MongoKit import Connection115116 connection = Connection()117118To insert data you can use the `insert` method. We have to get a119collection first, this is somewhat the same as a table in the SQL world.120121>>> collection = connection['test'].users122>>> user = {'name': u'admin', 'email': u'admin@localhost'}123>>> collection.insert(user)124125print list(collection.find())126print collection.find_one({'name': u'admin'})127128MongoKit will automatically commit for us.129130To query your database, you use the collection directly:131132>>> list(collection.find())133[{u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'}]134>>> collection.find_one({'name': u'admin'})135{u'_id': ObjectId('4c271729e13823182f000000'), u'name': u'admin', u'email': u'admin@localhost'}136137These results are also dict-like objects:138139>>> r = collection.find_one({'name': u'admin'})140>>> r['email']141u'admin@localhost'142143For more information about MongoKit, head over to the144`website <http://bytebucket.org/namlook/mongokit/>`_.