Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

387 lines · 14.4 KiB

Last changed by

Merge pull request #392 from FND/docsRon DuPlainbefore adoption7ba5196

History of this file

Take it

1Flask Extension Development2===========================34Flask, being a microframework, often requires some repetitive steps to get5a third party library working.  Because very often these steps could be6abstracted to support multiple projects the `Flask Extension Registry`_7was created.89If you want to create your own Flask extension for something that does not10exist yet, this guide to extension development will help you get your11extension running in no time and to feel like users would expect your12extension to behave.1314.. _Flask Extension Registry: http://flask.pocoo.org/extensions/1516Anatomy of an Extension17-----------------------1819Extensions are all located in a package called ``flask_something``20where "something" is the name of the library you want to bridge.  So for21example if you plan to add support for a library named `simplexml` to22Flask, you would name your extension's package ``flask_simplexml``.2324The name of the actual extension (the human readable name) however would25be something like "Flask-SimpleXML".  Make sure to include the name26"Flask" somewhere in that name and that you check the capitalization.27This is how users can then register dependencies to your extension in28their `setup.py` files.2930Flask sets up a redirect package called :data:`flask.ext` where users31should import the extensions from.  If you for instance have a package32called ``flask_something`` users would import it as33``flask.ext.something``.  This is done to transition from the old34namespace packages.  See :ref:`ext-import-transition` for more details.3536But how do extensions look like themselves?  An extension has to ensure37that it works with multiple Flask application instances at once.  This is38a requirement because many people will use patterns like the39:ref:`app-factories` pattern to create their application as needed to aid40unittests and to support multiple configurations.  Because of that it is41crucial that your application supports that kind of behaviour.4243Most importantly the extension must be shipped with a `setup.py` file and44registered on PyPI.  Also the development checkout link should work so45that people can easily install the development version into their46virtualenv without having to download the library by hand.4748Flask extensions must be licensed as BSD or MIT or a more liberal license49to be enlisted on the Flask Extension Registry.  Keep in mind that the50Flask Extension Registry is a moderated place and libraries will be51reviewed upfront if they behave as required.5253"Hello Flaskext!"54-----------------5556So let's get started with creating such a Flask extension.  The extension57we want to create here will provide very basic support for SQLite3.5859First we create the following folder structure::6061    flask-sqlite3/62        flask_sqlite3.py63        LICENSE64        README6566Here's the contents of the most important files:6768setup.py69````````7071The next file that is absolutely required is the `setup.py` file which is72used to install your Flask extension.  The following contents are73something you can work with::7475    """76    Flask-SQLite377    -------------7879    This is the description for that library80    """81    from setuptools import setup828384    setup(85        name='Flask-SQLite3',86        version='1.0',87        url='http://example.com/flask-sqlite3/',88        license='BSD',89        author='Your Name',90        author_email='your-email@example.com',91        description='Very short description',92        long_description=__doc__,93        py_modules=['flask_sqlite3'],94        # if you would be using a package instead use packages instead95        # of py_modules:96        # packages=['flask_sqlite3'],97        zip_safe=False,98        include_package_data=True,99        platforms='any',100        install_requires=[101            'Flask'102        ],103        classifiers=[104            'Environment :: Web Environment',105            'Intended Audience :: Developers',106            'License :: OSI Approved :: BSD License',107            'Operating System :: OS Independent',108            'Programming Language :: Python',109            'Topic :: Internet :: WWW/HTTP :: Dynamic Content',110            'Topic :: Software Development :: Libraries :: Python Modules'111        ]112    )113114That's a lot of code but you can really just copy/paste that from existing115extensions and adapt.116117flask_sqlite3.py118````````````````119120Now this is where your extension code goes.  But how exactly should such121an extension look like?  What are the best practices?  Continue reading122for some insight.123124Initializing Extensions125-----------------------126127Many extensions will need some kind of initialization step.  For example,128consider your application is currently connecting to SQLite like the129documentation suggests (:ref:`sqlite3`) you will need to provide a few130functions and before / after request handlers.  So how does the extension131know the name of the application object?132133Quite simple: you pass it to it.134135There are two recommended ways for an extension to initialize:136137initialization functions:138    If your extension is called `helloworld` you might have a function139    called ``init_helloworld(app[, extra_args])`` that initializes the140    extension for that application.  It could attach before / after141    handlers etc.142143classes:144    Classes work mostly like initialization functions but can later be145    used to further change the behaviour.  For an example look at how the146    `OAuth extension`_ works: there is an `OAuth` object that provides147    some helper functions like `OAuth.remote_app` to create a reference to148    a remote application that uses OAuth.149150What to use depends on what you have in mind.  For the SQLite 3 extension151we will use the class-based approach because it will provide users with a152manager object that handles opening and closing database connections.153154The Extension Code155------------------156157Here's the contents of the `flask_sqlite3.py` for copy/paste::158159    from __future__ import absolute_import160    import sqlite3161162    from flask import _request_ctx_stack163164    class SQLite3(object):165166        def __init__(self, app):167            self.app = app168            self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')169            self.app.teardown_request(self.teardown_request)170            self.app.before_request(self.before_request)171172        def connect(self):173            return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])174175        def before_request(self):176            ctx = _request_ctx_stack.top177            ctx.sqlite3_db = self.connect()178179        def teardown_request(self, exception):180            ctx = _request_ctx_stack.top181            ctx.sqlite3_db.close()182183        def get_db(self):184            ctx = _request_ctx_stack.top185            if ctx is not None:186                return ctx.sqlite3_db187188So here's what these lines of code do:1891901.  The ``__future__`` import is necessary to activate absolute imports.191    Otherwise we could not call our module `sqlite3.py` and import the192    top-level `sqlite3` module which actually implements the connection to193    SQLite.1942.  We create a class for our extension that requires a supplied `app` object,195    sets a configuration for the database if it's not there196    (:meth:`dict.setdefault`), and attaches `before_request` and197    `teardown_request` handlers.1983.  Next, we define a `connect` function that opens a database connection.1994.  Then we set up the request handlers we bound to the app above.  Note here200    that we're attaching our database connection to the top request context via201    `_request_ctx_stack.top`. Extensions should use the top context and not the202    `g` object to store things like database connections.2035.  Finally, we add a `get_db` function that simplifies access to the context's204    database.205206So why did we decide on a class-based approach here?  Because using our207extension looks something like this::208209    from flask import Flask210    from flask_sqlite3 import SQLite3211212    app = Flask(__name__)213    app.config.from_pyfile('the-config.cfg')214    manager = SQLite3(app)215    db = manager.get_db()216217You can then use the database from views like this::218219    @app.route('/')220    def show_all():221        cur = db.cursor()222        cur.execute(...)223224Opening a database connection from outside a view function is simple.225226>>> from yourapplication import db227>>> cur = db.cursor()228>>> cur.execute(...)229230Adding an `init_app` Function231-----------------------------232233In practice, you'll almost always want to permit users to initialize your234extension and provide an app object after the fact. This can help avoid235circular import problems when a user is breaking their app into multiple files.236Our extension could add an `init_app` function as follows::237238    class SQLite3(object):239240        def __init__(self, app=None):241            if app is not None:242                self.app = app243                self.init_app(self.app)244            else:245                self.app = None246247        def init_app(self, app):248            self.app = app249            self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')250            self.app.teardown_request(self.teardown_request)251            self.app.before_request(self.before_request)252253        def connect(self):254            return sqlite3.connect(app.config['SQLITE3_DATABASE'])255256        def before_request(self):257            ctx = _request_ctx_stack.top258            ctx.sqlite3_db = self.connect()259260        def teardown_request(self, exception):261            ctx = _request_ctx_stack.top262            ctx.sqlite3_db.close()263264        def get_db(self):265            ctx = _request_ctx_stack.top266            if ctx is not None:267                return ctx.sqlite3_db268269The user could then initialize the extension in one file::270271    manager = SQLite3()272273and bind their app to the extension in another file::274275    manager.init_app(app)276277End-Of-Request Behavior278-----------------------279280Due to the change in Flask 0.7 regarding functions that are run at the end281of the request your extension will have to be extra careful there if it282wants to continue to support older versions of Flask.  The following283pattern is a good way to support both::284285    def close_connection(response):286        ctx = _request_ctx_stack.top287        ctx.sqlite3_db.close()288        return response289290    if hasattr(app, 'teardown_request'):291        app.teardown_request(close_connection)292    else:293        app.after_request(close_connection)294295Strictly speaking the above code is wrong, because teardown functions are296passed the exception and typically don't return anything.  However because297the return value is discarded this will just work assuming that the code298in between does not touch the passed parameter.299300Learn from Others301-----------------302303This documentation only touches the bare minimum for extension304development.  If you want to learn more, it's a very good idea to check305out existing extensions on the `Flask Extension Registry`_.  If you feel306lost there is still the `mailinglist`_ and the `IRC channel`_ to get some307ideas for nice looking APIs.  Especially if you do something nobody before308you did, it might be a very good idea to get some more input.  This not309only to get an idea about what people might want to have from an310extension, but also to avoid having multiple developers working on pretty311much the same side by side.312313Remember: good API design is hard, so introduce your project on the314mailinglist, and let other developers give you a helping hand with315designing the API.316317The best Flask extensions are extensions that share common idioms for the318API.  And this can only work if collaboration happens early.319320Approved Extensions321-------------------322323Flask also has the concept of approved extensions.  Approved extensions324are tested as part of Flask itself to ensure extensions do not break on325new releases.  These approved extensions are listed on the `Flask326Extension Registry`_ and marked appropriately.  If you want your own327extension to be approved you have to follow these guidelines:3283291.  An approved Flask extension must provide exactly one package or module330    named ``flask_extensionname``.  They might also reside inside a331    ``flaskext`` namespace packages though this is discouraged now.3322.  It must ship a testing suite that can either be invoked with ``make test``333    or ``python setup.py test``.  For test suites invoked with ``make334    test`` the extension has to ensure that all dependencies for the test335    are installed automatically, in case of ``python setup.py test``336    dependencies for tests alone can be specified in the `setup.py`337    file.  The test suite also has to be part of the distribution.3383.  APIs of approved extensions will be checked for the following339    characteristics:340341    -   an approved extension has to support multiple applications342        running in the same Python process.343    -   it must be possible to use the factory pattern for creating344        applications.3453464.  The license must be BSD/MIT/WTFPL licensed.3475.  The naming scheme for official extensions is *Flask-ExtensionName* or348    *ExtensionName-Flask*.3496.  Approved extensions must define all their dependencies in the350    `setup.py` file unless a dependency cannot be met because it is not351    available on PyPI.3527.  The extension must have documentation that uses one of the two Flask353    themes for Sphinx documentation.3548.  The setup.py description (and thus the PyPI description) has to355    link to the documentation, website (if there is one) and there356    must be a link to automatically install the development version357    (``PackageName==dev``).3589.  The ``zip_safe`` flag in the setup script must be set to ``False``,359    even if the extension would be safe for zipping.36010. An extension currently has to support Python 2.5, 2.6 as well as361    Python 2.7362363364.. _ext-import-transition:365366Extension Import Transition367---------------------------368369For a while we recommended using namespace packages for Flask extensions.370This turned out to be problematic in practice because many different371competing namespace package systems exist and pip would automatically372switch between different systems and this caused a lot of problems for373users.374375Instead we now recommend naming packages ``flask_foo`` instead of the now376deprecated ``flaskext.foo``.  Flask 0.8 introduces a redirect import377system that lets uses import from ``flask.ext.foo`` and it will try378``flask_foo`` first and if that fails ``flaskext.foo``.379380Flask extensions should urge users to import from ``flask.ext.foo``381instead of ``flask_foo`` or ``flaskext_foo`` so that extensions can382transition to the new package name without affecting users.383384385.. _OAuth extension: http://packages.python.org/Flask-OAuth/386.. _mailinglist: http://flask.pocoo.org/mailinglist/387.. _IRC channel: http://flask.pocoo.org/community/irc/