Replace MongoKit by MongoEngine on docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Docs chapter "Patterns for Flask" has a section dedicated to MongoKit, but MongoKit lib seems unmaintained and is not compatible with recent versions of PyMongo. This commit replaces MongoKit guide with a new one using MongoEngine. Closes #2907
authored by Igor Ghisi · committed by David Lord · parent b276589 · Browse files · 3 files·+154 added−145 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+154 added−145 removed
- other:+154 added−145 removed
Provenance
- Commit
4e280b4- Tree
e781c72- Author
Igor Ghisi <igor@esss.com.br>- Committer
David Lord <davidism@gmail.com>- Parent
b276589
3 files changed+154 added−145 removed
modified:docs/patterns/index.rst+1 added-1 removed
32 unmodified lines33 flashing34 jquery35 errorpages36 lazyloading37- mongokit37+ mongoengine38 favicon39 streaming40 deferredcallbacks41 methodoverrides3 unmodified linesadded:docs/patterns/mongoengine.rst+153 added
1+.. mongoengine-pattern:2+3+MongoEngine 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 MongoEngine, a document mapper library, to8+integrate with MongoDB.9+10+This pattern requires a running MongoDB server, MongoEngine_ and Flask-MongoEngine_11+libraries installed::12+13+ pip install flask-mongoengine14+15+.. _MongoEngine: http://mongoengine.org16+.. _Flask-MongoEngine: http://docs.mongoengine.org/projects/flask-mongoengine/en/latest/>`_17+18+Configuration19+-------------20+21+Basic setup can be done by defining ``MONGODB_SETTINGS`` on App config and then22+creating a ``MongoEngine`` instance::23+24+ from flask import Flask25+ from flask_mongoengine import MongoEngine26+27+ app = Flask(__name__)28+ app.config['MONGODB_SETTINGS'] = {29+ 'host': "mongodb://localhost:27017/mydb"30+ }31+ db = MongoEngine(app)32+33+34+Mapping Documents35+-----------------36+37+To declare models that will represent your Mongo documents, just create a class that38+inherits from ``Document`` and declare each of the fields::39+40+ from mongoengine import *41+42+43+ class Movie(Document):44+45+ title = StringField(required=True)46+ year = IntField()47+ rated = StringField()48+ director = StringField()49+ actors = ListField()50+51+If the model has embedded documents, use ``EmbeddedDocument`` to defined the fields of52+the embedded document and ``EmbeddedDocumentField`` to declare it on the parent document::53+54+ class Imdb(EmbeddedDocument):55+56+ imdb_id = StringField()57+ rating = DecimalField()58+ votes = IntField()59+60+61+ class Movie(Document):62+63+ ...64+ imdb = EmbeddedDocumentField(Imdb)65+66+67+Creating Data68+-------------69+70+Just create the objects and call ``save()``::71+72+ bttf = Movie(title="Back To The Future", year=1985)73+ bttf.actors = [74+ "Michael J. Fox",75+ "Christopher Lloyd"76+ ]77+ bttf.imdb = Imdb(imdb_id="tt0088763", rating=8.5)78+ bttf.save()79+80+81+Queries82+-------83+84+Use the class ``objects`` attribute to make queries::85+86+ bttf = Movies.objects(title="Back To The Future").get() # Throw error if not unique87+88+``objects`` is an iterable. Query operators may be user by concatenating it with the document89+key using a double-underscore::90+91+ some_theron_movie = Movie.objects(actors__in=["Charlize Theron"]).first()92+93+ for recents in Movie.objects(year__gte=2017):94+ print(recents.title)95+96+Available operators are as follows:97+98+* ``ne`` -- not equal to99+* ``lt`` -- less than100+* ``lte`` -- less than or equal to101+* ``gt`` -- greater than102+* ``gte`` -- greater than or equal to103+* ``not`` -- negate a standard check, may be used before other operators (e.g.104+ ``Q(age__not__mod=5)``)105+* ``in`` -- value is in list (a list of values should be provided)106+* ``nin`` -- value is not in list (a list of values should be provided)107+* ``mod`` -- ``value % x == y``, where ``x`` and ``y`` are two provided values108+* ``all`` -- every item in list of values provided is in array109+* ``size`` -- the size of the array is110+* ``exists`` -- value for field exists111+112+String queries113+::::::::::::::114+115+The following operators are available as shortcuts to querying with regular116+expressions:117+118+* ``exact`` -- string field exactly matches value119+* ``iexact`` -- string field exactly matches value (case insensitive)120+* ``contains`` -- string field contains value121+* ``icontains`` -- string field contains value (case insensitive)122+* ``startswith`` -- string field starts with value123+* ``istartswith`` -- string field starts with value (case insensitive)124+* ``endswith`` -- string field ends with value125+* ``iendswith`` -- string field ends with value (case insensitive)126+* ``match`` -- performs an $elemMatch so you can match an entire document within an array127+128+Some Tips129+---------130+131+* Attributes can be set as ``unique``132+* ``MongoEngine`` creates the ``_id`` attribute automatically to acess ``ObjectIds``133+* You can add choices to string fields: ``StringField(choices=['Apple', 'Banana'])``134+* If you don't want your class name to be the same name as the collection, you can define135+ a ``meta`` class member and use the ``collection`` parameter::136+137+ class Movie(Document):138+139+ meta ={'collection': 'movie_documents'}140+141+Accessing PyMongo MongoClient142+-----------------------------143+144+If, for some reason, you want to access PyMongo instance, use ``get_connection`` function::145+146+ from mongoengine.connection import get_connection147+148+ conn = get_connection()149+ collection = conn.mydb.movie150+ collection({'title': u'Days of Thunder'})151+152+For more information about MongoEngine, head over to the153+`website <http://docs.mongoengine.org/>`_.deleted:docs/patterns/mongokit.rst-144 removed
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 a 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 behavior of MongoKit is the declarative one that is based on21-common ideas from Django or the SQLAlchemy declarative extension.22-23-Here an example :file:`app.py` module for your application::24-25- from flask import Flask26- from mongokit import Connection, Document27-28- # configuration29- MONGODB_HOST = 'localhost'30- MONGODB_PORT = 2701731-32- # create the little application object33- app = Flask(__name__)34- app.config.from_object(__name__)35-36- # connect to the database37- connection = Connection(app.config['MONGODB_HOST'],38- app.config['MONGODB_PORT'])39-40-41-To define your models, just subclass the `Document` class that is imported42-from MongoKit. If you've seen the SQLAlchemy pattern you may wonder why we do43-not have a session and even do not define a `init_db` function here. On the44-one hand, MongoKit does not have something like a session. This sometimes45-makes it more to type but also makes it blazingly fast. On the other hand,46-MongoDB is schemaless. This means you can modify the data structure from one47-insert query to the next without any problem. MongoKit is just schemaless48-too, but implements some validation to ensure data integrity.49-50-Here is an example document (put this also into :file:`app.py`, e.g.)::51-52- from mongokit import ValidationError53-54- 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 validate61-62- 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)74-75- # register the User document with our current connection76- connection.register([User])77-78-79-This example shows you how to define your schema (named structure), a80-validator for the maximum character length and uses a special MongoKit feature81-called `use_dot_notation`. Per default MongoKit behaves like a python82-dictionary but with `use_dot_notation` set to ``True`` you can use your83-documents like you use models in nearly any other ORM by using dots to84-separate between attributes.85-86-You can insert entries into the database like this:87-88->>> 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()95-96-Note that MongoKit is kinda strict with used column types, you must not use a97-common `str` type for either `name` or `email` but unicode.98-99-Querying is simple as well:100-101->>> list(collection.User.find())102-[<User u'admin'>]103->>> collection.User.find_one({'name': u'admin'})104-<User u'admin'>105-106-.. _MongoKit: http://bytebucket.org/namlook/mongokit/107-108-109-PyMongo Compatibility Layer110----------------------------111-112-If you just want to use PyMongo, you can do that with MongoKit as well. You113-may use this process if you need the best performance to get. Note that this114-example does not show how to couple it with Flask, see the above MongoKit code115-for examples::116-117- from MongoKit import Connection118-119- connection = Connection()120-121-To insert data you can use the `insert` method. We have to get a122-collection first, this is somewhat the same as a table in the SQL world.123-124->>> collection = connection['test'].users125->>> user = {'name': u'admin', 'email': u'admin@localhost'}126->>> collection.insert(user)127-128-MongoKit will automatically commit for us.129-130-To query your database, you use the collection directly:131-132->>> 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'}136-137-These results are also dict-like objects:138-139->>> r = collection.find_one({'name': u'admin'})140->>> r['email']141-u'admin@localhost'142-143-For more information about MongoKit, head over to the144-`website <https://github.com/namlook/mongokit>`_.