flask-mongoengine


Nameflask-mongoengine JSON
Version 1.0.0 PyPI version JSON
download
home_pagehttps://github.com/mongoengine/flask-mongoengine
SummaryFlask-MongoEngine is a Flask extension that provides integration with MongoEngine and WTF model forms.
upload_time2020-11-21 06:02:05
maintainer
docs_urlNone
authorRoss Lawley
requires_python
licenseBSD
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            Flask-MongoEngine
=================

A Flask extension that provides integration with `MongoEngine <http://mongoengine.org/>`_.
For more information on MongoEngine please check out the `MongoEngine Documentation <http://docs.mongoengine.org/>`_.

It handles connection management for your app.
You can also use `WTForms <http://wtforms.simplecodes.com/>`_ as model forms for your models.

Pre-requisite
=============

Make sure you have `wheel` installed::

    pip install wheel

Installing Flask-MongoEngine
============================

Install with **pip**::

    pip install flask-mongoengine

Configuration
=============

Basic setup is easy, just fetch the extension::

    from flask import Flask
    from flask_mongoengine import MongoEngine

    app = Flask(__name__)
    app.config.from_pyfile('the-config.cfg')
    db = MongoEngine(app)

Or, if you are setting up your database before your app is initialized, as is the case with application factories::

    from flask import Flask
    from flask_mongoengine import MongoEngine
    db = MongoEngine()
    ...
    app = Flask(__name__)
    app.config.from_pyfile('the-config.cfg')
    db.init_app(app)


By default, Flask-MongoEngine assumes that the `mongod` instance is running
on **localhost** on port **27017**, and you wish to connect to the database named **test**.

If MongoDB is running elsewhere, you should provide the `host` and `port` settings
in  the `'MONGODB_SETTINGS'` dictionary wih `app.config`.::

    app.config['MONGODB_SETTINGS'] = {
        'db': 'project1',
        'host': '192.168.1.35',
        'port': 12345
    }

If the database requires authentication, the `username` and `password`
arguments should be provided `'MONGODB_SETTINGS'` dictionary wih `app.config`.::

    app.config['MONGODB_SETTINGS'] = {
        'db': 'project1',
        'username':'webapp',
        'password':'pwd123'
    }

Uri style connections are also supported, just supply the uri as the `host`
in the `'MONGODB_SETTINGS'` dictionary with `app.config`. **Note that database name from uri has priority over name.** If uri presents and doesn't contain database name db setting entirely ignore and db name set to 'test'. ::

    app.config['MONGODB_SETTINGS'] = {
        'db': 'project1',
        'host': 'mongodb://localhost/database_name'
    }

Connection settings may also be provided individually by prefixing the setting with `'MONGODB_'` in the `app.config`.::

    app.config['MONGODB_DB'] = 'project1'
    app.config['MONGODB_HOST'] = '192.168.1.35'
    app.config['MONGODB_PORT'] = 12345
    app.config['MONGODB_USERNAME'] = 'webapp'
    app.config['MONGODB_PASSWORD'] = 'pwd123'

By default flask-mongoengine open the connection when extension is instanciated but you can configure it
to open connection only on first database access by setting the ``MONGODB_SETTINGS['connect']`` parameter
or its ``MONGODB_CONNECT`` flat equivalent to ``False``::

    app.config['MONGODB_SETTINGS'] = {
        'host': 'mongodb://localhost/database_name',
        'connect': False,
    }
    # or
    app.config['MONGODB_CONNECT'] = False

Custom Queryset
===============

flask-mongoengine attaches the following methods to Mongoengine's default QuerySet:

* **get_or_404**: works like .get(), but calls abort(404) if the object DoesNotExist.
  Optional arguments: *message* - custom message to display.
* **first_or_404**: same as above, except for .first().
  Optional arguments: *message* - custom message to display.
* **paginate**: paginates the QuerySet. Takes two arguments, *page* and *per_page*.
* **paginate_field**: paginates a field from one document in the QuerySet.
  Arguments: *field_name*, *doc_id*, *page*, *per_page*.

Examples::

    # 404 if object doesn't exist
    def view_todo(todo_id):
        todo = Todo.objects.get_or_404(_id=todo_id)
    ..

    # Paginate through todo
    def view_todos(page=1):
        paginated_todos = Todo.objects.paginate(page=page, per_page=10)

    # Paginate through tags of todo
    def view_todo_tags(todo_id, page=1):
        todo = Todo.objects.get_or_404(_id=todo_id)
        paginated_tags = todo.paginate_field('tags', page, per_page=10)

Properties of the pagination object include: iter_pages, next, prev, has_next,
has_prev, next_num, prev_num.

In the template::

    {# Display a page of todos #}
    <ul>
        {% for todo in paginated_todos.items %}
            <li>{{ todo.title }}</li>
        {% endfor %}
    </ul>

    {# Macro for creating navigation links #}
    {% macro render_navigation(pagination, endpoint) %}
      <div class=pagination>
      {% for page in pagination.iter_pages() %}
        {% if page %}
          {% if page != pagination.page %}
            <a href="{{ url_for(endpoint, page=page) }}">{{ page }}</a>
          {% else %}
            <strong>{{ page }}</strong>
          {% endif %}
        {% else %}
          <span class=ellipsis>…</span>
        {% endif %}
      {% endfor %}
      </div>
    {% endmacro %}

    {{ render_navigation(paginated_todos, 'view_todos') }}


MongoEngine and WTForms
=======================

flask-mongoengine automatically generates WTForms from MongoEngine models::

    from flask_mongoengine.wtf import model_form

    class User(db.Document):
        email = db.StringField(required=True)
        first_name = db.StringField(max_length=50)
        last_name = db.StringField(max_length=50)

    class Content(db.EmbeddedDocument):
        text = db.StringField()
        lang = db.StringField(max_length=3)

    class Post(db.Document):
        title = db.StringField(max_length=120, required=True, validators=[validators.InputRequired(message='Missing title.'),])
        author = db.ReferenceField(User)
        tags = db.ListField(db.StringField(max_length=30))
        content = db.EmbeddedDocumentField(Content)

    PostForm = model_form(Post)

    def add_post(request):
        form = PostForm(request.POST)
        if request.method == 'POST' and form.validate():
            # do something
            redirect('done')
        return render_template('add_post.html', form=form)

For each MongoEngine field, the most appropriate WTForm field is used.
Parameters allow the user to provide hints if the conversion is not implicit::

    PostForm = model_form(Post, field_args={'title': {'textarea': True}})

Supported parameters:

For fields with `choices`:

- `multiple` to use a SelectMultipleField
- `radio` to use a RadioField

For `StringField`:

- `password` to use a PasswordField
- `textarea` to use a TextAreaField

For `ListField`:

- `min_entries` to set the minimal number of entries

(By default, a StringField is converted into a TextAreaField if and only if it has no max_length.)


Supported fields
----------------

* StringField
* BinaryField
* URLField
* EmailField
* IntField
* FloatField
* DecimalField
* BooleanField
* DateTimeField
* **ListField** (using wtforms.fields.FieldList )
* SortedListField (duplicate ListField)
* **EmbeddedDocumentField** (using wtforms.fields.FormField and generating inline Form)
* **ReferenceField** (using wtforms.fields.SelectFieldBase with options loaded from QuerySet or Document)
* DictField

Not currently supported field types:
------------------------------------

* ObjectIdField
* GeoLocationField
* GenericReferenceField

Session Interface
=================

To use MongoEngine as your session store simple configure the session interface::

    from flask_mongoengine import MongoEngine, MongoEngineSessionInterface

    app = Flask(__name__)
    db = MongoEngine(app)
    app.session_interface = MongoEngineSessionInterface(db)


Debug Toolbar Panel
===================

.. image:: _static/debugtoolbar.png
  :target: #debug-toolbar-panel

If you use the Flask-DebugToolbar you can add
`'flask_mongoengine.panels.MongoDebugPanel'` to the `DEBUG_TB_PANELS` config
list and then it will automatically track your queries::

    from flask import Flask
    from flask_debugtoolbar import DebugToolbarExtension

    app = Flask(__name__)
    app.config['DEBUG_TB_PANELS'] = ['flask_mongoengine.panels.MongoDebugPanel']
    db = MongoEngine(app)
    toolbar = DebugToolbarExtension(app)



Upgrading
=========

0.6 to 0.7
----------

`ListFieldPagination` order of arguments have been changed to be more logical::

    # Old order
    ListFieldPagination(self, queryset, field_name, doc_id, page, per_page, total)

    # New order
    ListFieldPagination(self, queryset, doc_id, field_name, page, per_page, total)


Credits
=======

Inspired by two repos:

`danjac <https://bitbucket.org/danjac/flask-mongoengine>`_
`maratfm <https://bitbucket.org/maratfm/wtforms>`_



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/mongoengine/flask-mongoengine",
    "name": "flask-mongoengine",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Ross Lawley",
    "author_email": "ross.lawley@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/40/7a/415fa435493ec113edcdc5d0568f5167b06e8d1d878d73b2d2e2d9d41c7f/flask-mongoengine-1.0.0.tar.gz",
    "platform": "any",
    "description": "Flask-MongoEngine\n=================\n\nA Flask extension that provides integration with `MongoEngine <http://mongoengine.org/>`_.\nFor more information on MongoEngine please check out the `MongoEngine Documentation <http://docs.mongoengine.org/>`_.\n\nIt handles connection management for your app.\nYou can also use `WTForms <http://wtforms.simplecodes.com/>`_ as model forms for your models.\n\nPre-requisite\n=============\n\nMake sure you have `wheel` installed::\n\n    pip install wheel\n\nInstalling Flask-MongoEngine\n============================\n\nInstall with **pip**::\n\n    pip install flask-mongoengine\n\nConfiguration\n=============\n\nBasic setup is easy, just fetch the extension::\n\n    from flask import Flask\n    from flask_mongoengine import MongoEngine\n\n    app = Flask(__name__)\n    app.config.from_pyfile('the-config.cfg')\n    db = MongoEngine(app)\n\nOr, if you are setting up your database before your app is initialized, as is the case with application factories::\n\n    from flask import Flask\n    from flask_mongoengine import MongoEngine\n    db = MongoEngine()\n    ...\n    app = Flask(__name__)\n    app.config.from_pyfile('the-config.cfg')\n    db.init_app(app)\n\n\nBy default, Flask-MongoEngine assumes that the `mongod` instance is running\non **localhost** on port **27017**, and you wish to connect to the database named **test**.\n\nIf MongoDB is running elsewhere, you should provide the `host` and `port` settings\nin  the `'MONGODB_SETTINGS'` dictionary wih `app.config`.::\n\n    app.config['MONGODB_SETTINGS'] = {\n        'db': 'project1',\n        'host': '192.168.1.35',\n        'port': 12345\n    }\n\nIf the database requires authentication, the `username` and `password`\narguments should be provided `'MONGODB_SETTINGS'` dictionary wih `app.config`.::\n\n    app.config['MONGODB_SETTINGS'] = {\n        'db': 'project1',\n        'username':'webapp',\n        'password':'pwd123'\n    }\n\nUri style connections are also supported, just supply the uri as the `host`\nin the `'MONGODB_SETTINGS'` dictionary with `app.config`. **Note that database name from uri has priority over name.** If uri presents and doesn't contain database name db setting entirely ignore and db name set to 'test'. ::\n\n    app.config['MONGODB_SETTINGS'] = {\n        'db': 'project1',\n        'host': 'mongodb://localhost/database_name'\n    }\n\nConnection settings may also be provided individually by prefixing the setting with `'MONGODB_'` in the `app.config`.::\n\n    app.config['MONGODB_DB'] = 'project1'\n    app.config['MONGODB_HOST'] = '192.168.1.35'\n    app.config['MONGODB_PORT'] = 12345\n    app.config['MONGODB_USERNAME'] = 'webapp'\n    app.config['MONGODB_PASSWORD'] = 'pwd123'\n\nBy default flask-mongoengine open the connection when extension is instanciated but you can configure it\nto open connection only on first database access by setting the ``MONGODB_SETTINGS['connect']`` parameter\nor its ``MONGODB_CONNECT`` flat equivalent to ``False``::\n\n    app.config['MONGODB_SETTINGS'] = {\n        'host': 'mongodb://localhost/database_name',\n        'connect': False,\n    }\n    # or\n    app.config['MONGODB_CONNECT'] = False\n\nCustom Queryset\n===============\n\nflask-mongoengine attaches the following methods to Mongoengine's default QuerySet:\n\n* **get_or_404**: works like .get(), but calls abort(404) if the object DoesNotExist.\n  Optional arguments: *message* - custom message to display.\n* **first_or_404**: same as above, except for .first().\n  Optional arguments: *message* - custom message to display.\n* **paginate**: paginates the QuerySet. Takes two arguments, *page* and *per_page*.\n* **paginate_field**: paginates a field from one document in the QuerySet.\n  Arguments: *field_name*, *doc_id*, *page*, *per_page*.\n\nExamples::\n\n    # 404 if object doesn't exist\n    def view_todo(todo_id):\n        todo = Todo.objects.get_or_404(_id=todo_id)\n    ..\n\n    # Paginate through todo\n    def view_todos(page=1):\n        paginated_todos = Todo.objects.paginate(page=page, per_page=10)\n\n    # Paginate through tags of todo\n    def view_todo_tags(todo_id, page=1):\n        todo = Todo.objects.get_or_404(_id=todo_id)\n        paginated_tags = todo.paginate_field('tags', page, per_page=10)\n\nProperties of the pagination object include: iter_pages, next, prev, has_next,\nhas_prev, next_num, prev_num.\n\nIn the template::\n\n    {# Display a page of todos #}\n    <ul>\n        {% for todo in paginated_todos.items %}\n            <li>{{ todo.title }}</li>\n        {% endfor %}\n    </ul>\n\n    {# Macro for creating navigation links #}\n    {% macro render_navigation(pagination, endpoint) %}\n      <div class=pagination>\n      {% for page in pagination.iter_pages() %}\n        {% if page %}\n          {% if page != pagination.page %}\n            <a href=\"{{ url_for(endpoint, page=page) }}\">{{ page }}</a>\n          {% else %}\n            <strong>{{ page }}</strong>\n          {% endif %}\n        {% else %}\n          <span class=ellipsis>\u2026</span>\n        {% endif %}\n      {% endfor %}\n      </div>\n    {% endmacro %}\n\n    {{ render_navigation(paginated_todos, 'view_todos') }}\n\n\nMongoEngine and WTForms\n=======================\n\nflask-mongoengine automatically generates WTForms from MongoEngine models::\n\n    from flask_mongoengine.wtf import model_form\n\n    class User(db.Document):\n        email = db.StringField(required=True)\n        first_name = db.StringField(max_length=50)\n        last_name = db.StringField(max_length=50)\n\n    class Content(db.EmbeddedDocument):\n        text = db.StringField()\n        lang = db.StringField(max_length=3)\n\n    class Post(db.Document):\n        title = db.StringField(max_length=120, required=True, validators=[validators.InputRequired(message='Missing title.'),])\n        author = db.ReferenceField(User)\n        tags = db.ListField(db.StringField(max_length=30))\n        content = db.EmbeddedDocumentField(Content)\n\n    PostForm = model_form(Post)\n\n    def add_post(request):\n        form = PostForm(request.POST)\n        if request.method == 'POST' and form.validate():\n            # do something\n            redirect('done')\n        return render_template('add_post.html', form=form)\n\nFor each MongoEngine field, the most appropriate WTForm field is used.\nParameters allow the user to provide hints if the conversion is not implicit::\n\n    PostForm = model_form(Post, field_args={'title': {'textarea': True}})\n\nSupported parameters:\n\nFor fields with `choices`:\n\n- `multiple` to use a SelectMultipleField\n- `radio` to use a RadioField\n\nFor `StringField`:\n\n- `password` to use a PasswordField\n- `textarea` to use a TextAreaField\n\nFor `ListField`:\n\n- `min_entries` to set the minimal number of entries\n\n(By default, a StringField is converted into a TextAreaField if and only if it has no max_length.)\n\n\nSupported fields\n----------------\n\n* StringField\n* BinaryField\n* URLField\n* EmailField\n* IntField\n* FloatField\n* DecimalField\n* BooleanField\n* DateTimeField\n* **ListField** (using wtforms.fields.FieldList )\n* SortedListField (duplicate ListField)\n* **EmbeddedDocumentField** (using wtforms.fields.FormField and generating inline Form)\n* **ReferenceField** (using wtforms.fields.SelectFieldBase with options loaded from QuerySet or Document)\n* DictField\n\nNot currently supported field types:\n------------------------------------\n\n* ObjectIdField\n* GeoLocationField\n* GenericReferenceField\n\nSession Interface\n=================\n\nTo use MongoEngine as your session store simple configure the session interface::\n\n    from flask_mongoengine import MongoEngine, MongoEngineSessionInterface\n\n    app = Flask(__name__)\n    db = MongoEngine(app)\n    app.session_interface = MongoEngineSessionInterface(db)\n\n\nDebug Toolbar Panel\n===================\n\n.. image:: _static/debugtoolbar.png\n  :target: #debug-toolbar-panel\n\nIf you use the Flask-DebugToolbar you can add\n`'flask_mongoengine.panels.MongoDebugPanel'` to the `DEBUG_TB_PANELS` config\nlist and then it will automatically track your queries::\n\n    from flask import Flask\n    from flask_debugtoolbar import DebugToolbarExtension\n\n    app = Flask(__name__)\n    app.config['DEBUG_TB_PANELS'] = ['flask_mongoengine.panels.MongoDebugPanel']\n    db = MongoEngine(app)\n    toolbar = DebugToolbarExtension(app)\n\n\n\nUpgrading\n=========\n\n0.6 to 0.7\n----------\n\n`ListFieldPagination` order of arguments have been changed to be more logical::\n\n    # Old order\n    ListFieldPagination(self, queryset, field_name, doc_id, page, per_page, total)\n\n    # New order\n    ListFieldPagination(self, queryset, doc_id, field_name, page, per_page, total)\n\n\nCredits\n=======\n\nInspired by two repos:\n\n`danjac <https://bitbucket.org/danjac/flask-mongoengine>`_\n`maratfm <https://bitbucket.org/maratfm/wtforms>`_\n\n\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "Flask-MongoEngine is a Flask extension that provides integration with MongoEngine and WTF model forms.",
    "version": "1.0.0",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "bc08cd2052b0bfb636c5e47bae31ea4b089ace44cdd0c2cc4fd800c8ff63d95f",
                "md5": "490e57d96e3aee35301b3e55d556e253",
                "sha256": "2db13140ce7f61a935e75268190450d5ecc9b60a7310fd289f9511835aa105d4"
            },
            "downloads": -1,
            "filename": "flask_mongoengine-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "490e57d96e3aee35301b3e55d556e253",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 25746,
            "upload_time": "2020-11-21T06:02:04",
            "upload_time_iso_8601": "2020-11-21T06:02:04.318446Z",
            "url": "https://files.pythonhosted.org/packages/bc/08/cd2052b0bfb636c5e47bae31ea4b089ace44cdd0c2cc4fd800c8ff63d95f/flask_mongoengine-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "407a415fa435493ec113edcdc5d0568f5167b06e8d1d878d73b2d2e2d9d41c7f",
                "md5": "b131f26b11f6ca2874dabd072e127472",
                "sha256": "ce68726d2be8d88006e88f17e4be3b7ad07c79ca8dedb60653d3dab5d9485840"
            },
            "downloads": -1,
            "filename": "flask-mongoengine-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "b131f26b11f6ca2874dabd072e127472",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 117656,
            "upload_time": "2020-11-21T06:02:05",
            "upload_time_iso_8601": "2020-11-21T06:02:05.984484Z",
            "url": "https://files.pythonhosted.org/packages/40/7a/415fa435493ec113edcdc5d0568f5167b06e8d1d878d73b2d2e2d9d41c7f/flask-mongoengine-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2020-11-21 06:02:05",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "mongoengine",
    "github_project": "flask-mongoengine",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "flask-mongoengine"
}
        
Elapsed time: 0.70703s