Merge branch '1.0-maintenance'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parents 3b45b82, 0f56c0c · Browse files · 11 files·+173 added−162 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+173 added−162 removed
- other:+173 added−162 removed
Provenance
- Commit
ac6746d- Tree
67f5505- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
3b45b82- Parent 2
0f56c0c
11 files changed+173 added−162 removed
modified:docs/patterns/index.rst+1 added-1 removed
32 unmodified lines33 flashing34 jquery35 errorpages36 lazyloading37- mongokit37+ mongoengine38 favicon39 streaming40 deferredcallbacks41 methodoverrides4 unmodified linesmodified:docs/patterns/jquery.rst+1 added-1 removed
103 unmodified lines104 def index():105 return render_template('index.html')106 107 As you can see I also added an `index` method here that renders a108-template. This template will load jQuery as above and have a little form108+template. This template will load jQuery as above and have a little form where109 we can add two numbers and a link to trigger the function on the server110 side.111 112 Note that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here55 unmodified linesadded:docs/patterns/mongoengine.rst+103 added
1+MongoDB with MongoEngine2+========================3+4+Using a document database like MongoDB is a common alternative to5+relational SQL databases. This pattern shows how to use6+`MongoEngine`_, a document mapper library, to integrate with MongoDB.7+8+A running MongoDB server and `Flask-MongoEngine`_ are required. ::9+10+ pip install flask-mongoengine11+12+.. _MongoEngine: http://mongoengine.org13+.. _Flask-MongoEngine: https://flask-mongoengine.readthedocs.io14+15+16+Configuration17+-------------18+19+Basic setup can be done by defining ``MONGODB_SETTINGS`` on20+``app.config`` and creating a ``MongoEngine`` instance. ::21+22+ from flask import Flask23+ from flask_mongoengine import MongoEngine24+25+ app = Flask(__name__)26+ app.config['MONGODB_SETTINGS'] = {27+ "db": "myapp",28+ }29+ db = MongoEngine(app)30+31+32+Mapping Documents33+-----------------34+35+To declare a model that represents a Mongo document, create a class that36+inherits from ``Document`` and declare each of the fields. ::37+38+ import mongoengine as me39+40+ 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()46+47+If the document has nested fields, use ``EmbeddedDocument`` to48+defined the fields of the embedded document and49+``EmbeddedDocumentField`` to declare it on the parent document. ::50+51+ class Imdb(me.EmbeddedDocument):52+ imdb_id = me.StringField()53+ rating = me.DecimalField()54+ votes = me.IntField()55+56+ class Movie(me.Document):57+ ...58+ imdb = me.EmbeddedDocumentField(Imdb)59+60+61+Creating Data62+-------------63+64+Instantiate your document class with keyword arguments for the fields.65+You can also assign values to the field attributes after instantiation.66+Then call ``doc.save()``. ::67+68+ 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()75+76+77+Queries78+-------79+80+Use the class ``objects`` attribute to make queries. A keyword argument81+looks for an equal value on the field. ::82+83+ bttf = Movies.objects(title="Back To The Future").get_or_404()84+85+Query operators may be used by concatenating them with the field name86+using a double-underscore. ``objects``, and queries returned by87+calling it, are iterable. ::88+89+ some_theron_movie = Movie.objects(actors__in=["Charlize Theron"]).first()90+91+ for recents in Movie.objects(year__gte=2017):92+ print(recents.title)93+94+95+Documentation96+-------------97+98+There are many more ways to define and query documents with MongoEngine.99+For more information, check out the `official documentation100+<MongoEngine_>`_.101+102+Flask-MongoEngine adds helpful utilities on top of MongoEngine. Check103+out their `documentation <Flask-MongoEngine_>`_ as well.modified:docs/patterns/mongokit.rst+5 added-142 removed
1-.. mongokit-pattern:1+:orphan:2 3-MongoKit in Flask4-=================3+MongoDB with MongoKit4+=====================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: https://github.com/namlook/mongokit107-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>`_.6+MongoKit is no longer maintained. See :doc:`/patterns/mongoengine`7+instead.modified:docs/patterns/packages.rst+5 added-5 removed
1 unmodified line2 3 Larger Applications4 ===================5 6-For larger applications it's a good idea to use a package instead of a7-module. That is quite simple. Imagine a small application looks like8-this::6+Imagine a simple flask application structure that looks like this::7 8 /yourapplication9 yourapplication.py10 /static3 unmodified lines14 index.html15 login.html16 ...17 18+While this is fine for small applications, for larger applications19+it's a good idea to use a package instead of a module.20-The :ref:`tutorial <tutorial>` is structured this way, see the21-:gh:`example code <examples/tutorial>`.20+The :ref:`tutorial <tutorial>` is structured to use the package pattern,21+see the :gh:`example code <examples/tutorial>`.22 23 Simple Packages24 ---------------25 118 unmodified linesmodified:docs/tutorial/factory.rst+2 added-1 removed
125 unmodified lines126 -------------------127 128 Now you can run your application using the ``flask`` command. From the129 terminal, tell Flask where to find your application, then run it in130-development mode.130+development mode. Remember, you should still be in the top-level131+``flask-tutorial`` directory, not the ``flaskr`` package.132 133 Development mode shows an interactive debugger whenever a page raises an134 exception, and restarts the server whenever you make changes to the135 code. You can leave it running and just reload the browser page as you43 unmodified linesmodified:docs/tutorial/install.rst+2 added-1 removed
106 unmodified lines107 wheel 0.30.0108 109 Nothing changes from how you've been running your project so far.110 ``FLASK_APP`` is still set to ``flaskr`` and ``flask run`` still runs111-the application.111+the application, but you can call it from anywhere, not just the112+``flask-tutorial`` directory.113 114 Continue to :doc:`tests`.modified:docs/config.rst+41 added-3 removed
299 unmodified lines300 .. py:data:: JSON_AS_ASCII301 302 Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON303 will be returned as a Unicode string, or encoded as ``UTF-8`` by304- ``jsonify``. This has security implications when rendering the JSON in305- to JavaScript in templates, and should typically remain enabled.304+ ``jsonify``. This has security implications when rendering the JSON into305+ JavaScript in templates, and should typically remain enabled.306 307 Default: ``True``308 309 .. py:data:: JSON_SORT_KEYS242 unmodified lines552 :meth:`~flask.Config.from_object`::553 554 app.config.from_object('configmodule.ProductionConfig')555 556+Note that :meth:`~flask.Config.from_object` does not instantiate the class557+object. If you need to instantiate the class, such as to access a property,558+then you must do so before calling :meth:`~flask.Config.from_object`::559+560+ from configmodule import ProductionConfig561+ app.config.from_object(ProductionConfig())562+563+ # Alternatively, import via string:564+ from werkzeug.utils import import_string565+ cfg = import_string('configmodule.ProductionConfig')()566+ app.config.from_object(cfg)567+568+Instantiating the configutation object allows you to use ``@property`` in569+your configuration classes::570+571+ class Config(object):572+ """Base config, uses staging database server."""573+ DEBUG = False574+ TESTING = False575+ DB_SERVER = '192.168.1.56'576+577+ @property578+ def DATABASE_URI(self): # Note: all caps579+ return 'mysql://user@{}/foo'.format(self.DB_SERVER)580+581+ class ProductionConfig(Config):582+ """Uses production database server."""583+ DB_SERVER = '192.168.19.32'584+585+ class DevelopmentConfig(Config):586+ DB_SERVER = 'localhost'587+ DEBUG = True588+589+ class TestingConfig(Config):590+ DB_SERVER = 'localhost'591+ DEBUG = True592+ DATABASE_URI = 'sqlite:///:memory:'593+594 There are many different ways and it's up to you how you want to manage595 your configuration files. However here a list of good recommendations:596 597 - Keep a default configuration in version control. Either populate the75 unmodified lines673 674 app = Flask(__name__, instance_relative_config=True)675 676 Here is a full example of how to configure Flask to preload the config639-from a module and then override the config from a file in the config677+from a module and then override the config from a file in the instance678 folder if it exists::679 680 app = Flask(__name__, instance_relative_config=True)681 app.config.from_object('yourapplication.default_settings')15 unmodified linesmodified:flask/config.py+4 added
154 unmodified lines155 app.config.from_object('yourapplication.default_config')156 from yourapplication import default_config157 app.config.from_object(default_config)158 159+ Nothing is done to the object before loading. If the object is a160+ class and has ``@property`` attributes, it needs to be161+ instantiated before being passed to this method.162+163 You should not use this function to load the actual configuration but164 rather configuration defaults. The actual config should be loaded165 with :meth:`from_pyfile` and ideally from a location not within the166 package because the package might be installed system wide.103 unmodified linesmodified:.travis.yml+8 added-7 removed
13 unmodified lines14 matrix:15 include:16 - env: TOXENV=docs-html17 - env: TOXENV=devel,lowest,codecov18+# disabled because before_install is too slow18- - os: osx19- language: generic20- env: TOXENV=py3,codecov21- cache:22- directories:23- - $HOME/Library/Caches/Homebrew24- - $HOME/Library/Caches/pip19+# - os: osx20+# language: generic21+# env: TOXENV=py3,codecov22+# cache:23+# directories:24+# - $HOME/Library/Caches/Homebrew25+# - $HOME/Library/Caches/pip26 allow_failures:27 - python: nightly28 - python: pypy3.5-6.029 - os: osx28 unmodified linesmodified:MANIFEST.in+1 added-1 removed
1-include Makefile CHANGES.rst LICENSE AUTHORS tox.ini1+include Makefile CHANGES.rst CONTRIBUTING.rst LICENSE AUTHORS tox.ini2 3 graft artwork4 graft tests5 graft examples6 unmodified lines