Skip to content
Myr

Merge pull request #2964 from igortg/2907-docs-update-mongo-pattern

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

authored by David Lord · committed by GitHub · parents b276589, edef8cb · Browse files · 3 files+109 added−143 removed
This commit

State

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

Trailers

  • Docs: replace MongoKit by MongoEngine on docs

Diff stats

3 files+109 added−143 removed

  • other:+109 added−143 removed

3 files+109 added−143 removed

modified:docs/patterns/index.rst+1 added-1 removed
32 unmodified lines
33 flashing34 jquery35 errorpages36 lazyloading37 mongokit37 mongoengine38 favicon39 streaming40 deferredcallbacks41 methodoverrides
3 unmodified lines
added:docs/patterns/mongoengine.rst+103 added
1MongoDB with MongoEngine2========================34Using a document database like MongoDB is a common alternative to5relational SQL databases. This pattern shows how to use6`MongoEngine`_, a document mapper library, to integrate with MongoDB.78A running MongoDB server and `Flask-MongoEngine`_ are required. ::910 pip install flask-mongoengine1112.. _MongoEngine: http://mongoengine.org13.. _Flask-MongoEngine: https://flask-mongoengine.readthedocs.io141516Configuration17-------------1819Basic setup can be done by defining ``MONGODB_SETTINGS`` on20``app.config`` and creating a ``MongoEngine`` instance. ::2122 from flask import Flask23 from flask_mongoengine import MongoEngine2425 app = Flask(__name__)26 app.config['MONGODB_SETTINGS'] = {27 "db": "myapp",28 }29 db = MongoEngine(app)303132Mapping Documents33-----------------3435To declare a model that represents a Mongo document, create a class that36inherits from ``Document`` and declare each of the fields. ::3738 import mongoengine as me3940 class Movie(me.Document):41 title = me.StringField(required=True)42 year = me.IntField()43 rated = me.StringField()44 director = me.StringField()45 actors = me.ListField()4647If the document has nested fields, use ``EmbeddedDocument`` to48defined the fields of the embedded document and49``EmbeddedDocumentField`` to declare it on the parent document. ::5051 class Imdb(me.EmbeddedDocument):52 imdb_id = me.StringField()53 rating = me.DecimalField()54 votes = me.IntField()5556 class Movie(me.Document):57 ...58 imdb = me.EmbeddedDocumentField(Imdb)596061Creating Data62-------------6364Instantiate your document class with keyword arguments for the fields.65You can also assign values to the field attributes after instantiation.66Then call ``doc.save()``. ::6768 bttf = Movie(title="Back To The Future", year=1985)69 bttf.actors = [70 "Michael J. Fox",71 "Christopher Lloyd"72 ]73 bttf.imdb = Imdb(imdb_id="tt0088763", rating=8.5)74 bttf.save()757677Queries78-------7980Use the class ``objects`` attribute to make queries. A keyword argument81looks for an equal value on the field. ::8283 bttf = Movies.objects(title="Back To The Future").get_or_404()8485Query operators may be used by concatenating them with the field name86using a double-underscore. ``objects``, and queries returned by87calling it, are iterable. ::8889 some_theron_movie = Movie.objects(actors__in=["Charlize Theron"]).first()9091 for recents in Movie.objects(year__gte=2017):92 print(recents.title)939495Documentation96-------------9798There are many more ways to define and query documents with MongoEngine.99For more information, check out the `official documentation100<MongoEngine_>`_.101102Flask-MongoEngine adds helpful utilities on top of MongoEngine. Check103out their `documentation <Flask-MongoEngine_>`_ as well.
modified:docs/patterns/mongokit.rst+5 added-142 removed
1.. mongokit-pattern:1:orphan:23MongoKit in Flask4=================3MongoDB with MongoKit4=====================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.2223Here an example :file:`app.py` module for your application::2425 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.4950Here is an example document (put this also into :file:`app.py`, e.g.)::5152 from mongokit import ValidationError5354 def max_length(length):55 def validate(value):56 if len(value) <= length:57 return True58 # must have %s in error format string to have mongokit place key in there59 raise ValidationError('%s must be at most {} characters long'.format(length))60 return validate6162 class User(Document):63 structure = {64 'name': unicode,65 'email': unicode,66 }67 validators = {68 'name': max_length(50),69 'email': max_length(120)70 }71 use_dot_notation = True72 def __repr__(self):73 return '<User %r>' % (self.name)7475 # register the User document with our current connection76 connection.register([User])777879This example shows you how to define your schema (named structure), a80validator for the maximum character length and uses a special MongoKit feature81called `use_dot_notation`. Per default MongoKit behaves like a python82dictionary but with `use_dot_notation` set to ``True`` you can use your83documents like you use models in nearly any other ORM by using dots to84separate between attributes.8586You can insert entries into the database like this:8788>>> from yourapplication.database import connection89>>> from yourapplication.models import User90>>> collection = connection['test'].users91>>> user = collection.User()92>>> user['name'] = u'admin'93>>> user['email'] = u'admin@localhost'94>>> user.save()9596Note that MongoKit is kinda strict with used column types, you must not use a97common `str` type for either `name` or `email` but unicode.9899Querying is simple as well:100101>>> list(collection.User.find())102[<User u'admin'>]103>>> collection.User.find_one({'name': u'admin'})104<User u'admin'>105106.. _MongoKit: http://bytebucket.org/namlook/mongokit/107108109PyMongo Compatibility Layer110---------------------------111112If you just want to use PyMongo, you can do that with MongoKit as well. You113may use this process if you need the best performance to get. Note that this114example does not show how to couple it with Flask, see the above MongoKit code115for examples::116117 from MongoKit import Connection118119 connection = Connection()120121To insert data you can use the `insert` method. We have to get a122collection first, this is somewhat the same as a table in the SQL world.123124>>> collection = connection['test'].users125>>> user = {'name': u'admin', 'email': u'admin@localhost'}126>>> collection.insert(user)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 <https://github.com/namlook/mongokit>`_.6MongoKit is no longer maintained. See :doc:`/patterns/mongoengine`7instead.