Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

370 lines · 14.1 KiB

Last changed by

Merge pull request #440 from jamesls/extension-docsRon DuPlainbefore adoptiona5d1cf4

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 an application that's currently connecting to SQLite like the129documentation suggests (:ref:`sqlite3`).  So how does the extension130know the name of the application object?131132Quite simple: you pass it to it.133134There are two recommended ways for an extension to initialize:135136initialization functions:137138    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:144145    Classes work mostly like initialization functions but can later be146    used to further change the behaviour.  For an example look at how the147    `OAuth extension`_ works: there is an `OAuth` object that provides148    some helper functions like `OAuth.remote_app` to create a reference to149    a remote application that uses OAuth.150151What to use depends on what you have in mind.  For the SQLite 3 extension152we will use the class-based approach because it will provide users with an153object that handles opening and closing database connections.154155The Extension Code156------------------157158Here's the contents of the `flask_sqlite3.py` for copy/paste::159160    import sqlite3161162    from flask import _request_ctx_stack163164165    class SQLite3(object):166167        def __init__(self, app=None):168            if app is not None:169                self.app = app170                self.init_app(self.app)171            else:172                self.app = None173174        def init_app(self, app):175            self.app = app176            self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')177            self.app.teardown_request(self.teardown_request)178            self.app.before_request(self.before_request)179180        def connect(self):181            return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])182183        def before_request(self):184            ctx = _request_ctx_stack.top185            ctx.sqlite3_db = self.connect()186187        def teardown_request(self, exception):188            ctx = _request_ctx_stack.top189            ctx.sqlite3_db.close()190191        @property192        def connection(self):193            ctx = _request_ctx_stack.top194            if ctx is not None:195                return ctx.sqlite3_db196197198So here's what these lines of code do:1992001.  The ``__init__`` method takes an optional app object and, if supplied, will201    call ``init_app``.2022.  The ``init_app`` method exists so that the ``SQLite3`` object can be203    instantiated without requiring an app object.  This method supports the204    factory pattern for creating applications.  The ``init_app`` will set the205    configuration for the database, defaulting to an in memory database if206    no configuration is supplied.  In addition, the ``init_app`` method attaches207    ``before_request`` and ``teardown_request`` handlers.2083.  Next, we define a ``connect`` method that opens a database connection.2094.  Then we set up the request handlers we bound to the app above.  Note here210    that we're attaching our database connection to the top request context via211    ``_request_ctx_stack.top``. Extensions should use the top context and not the212    ``g`` object to store things like database connections.2135.  Finally, we add a ``connection`` property that simplifies access to the context's214    database.215216So why did we decide on a class-based approach here?  Because using our217extension looks something like this::218219    from flask import Flask220    from flask_sqlite3 import SQLite3221222    app = Flask(__name__)223    app.config.from_pyfile('the-config.cfg')224    db = SQLite3(app)225226You can then use the database from views like this::227228    @app.route('/')229    def show_all():230        cur = db.connection.cursor()231        cur.execute(...)232233Additionally, the ``init_app`` method is used to support the factory pattern234for creating apps::235236    db = Sqlite3()237    # Then later on.238    app = create_app('the-config.cfg')239    db.init_app(app)240241Keep in mind that supporting this factory pattern for creating apps is required242for approved flask extensions (described below).243244245Using _request_ctx_stack246------------------------247248In the example above, before every request, a ``sqlite3_db`` variable is assigned249to ``_request_ctx_stack.top``.  In a view function, this variable is accessible250using the ``connection`` property of ``SQLite3``.  During the teardown of a251request, the ``sqlite3_db`` connection is closed.  By using this pattern, the252*same* connection to the sqlite3 database is accessible to anything that needs it253for the duration of the request.254255End-Of-Request Behavior256-----------------------257258Due to the change in Flask 0.7 regarding functions that are run at the end259of the request your extension will have to be extra careful there if it260wants to continue to support older versions of Flask.  The following261pattern is a good way to support both::262263    def close_connection(response):264        ctx = _request_ctx_stack.top265        ctx.sqlite3_db.close()266        return response267268    if hasattr(app, 'teardown_request'):269        app.teardown_request(close_connection)270    else:271        app.after_request(close_connection)272273274Strictly speaking the above code is wrong, because teardown functions are275passed the exception and typically don't return anything.  However because276the return value is discarded this will just work assuming that the code277in between does not touch the passed parameter.278279Learn from Others280-----------------281282This documentation only touches the bare minimum for extension283development.  If you want to learn more, it's a very good idea to check284out existing extensions on the `Flask Extension Registry`_.  If you feel285lost there is still the `mailinglist`_ and the `IRC channel`_ to get some286ideas for nice looking APIs.  Especially if you do something nobody before287you did, it might be a very good idea to get some more input.  This not288only to get an idea about what people might want to have from an289extension, but also to avoid having multiple developers working on pretty290much the same side by side.291292Remember: good API design is hard, so introduce your project on the293mailinglist, and let other developers give you a helping hand with294designing the API.295296The best Flask extensions are extensions that share common idioms for the297API.  And this can only work if collaboration happens early.298299Approved Extensions300-------------------301302Flask also has the concept of approved extensions.  Approved extensions303are tested as part of Flask itself to ensure extensions do not break on304new releases.  These approved extensions are listed on the `Flask305Extension Registry`_ and marked appropriately.  If you want your own306extension to be approved you have to follow these guidelines:3073080.  An approved Flask extension requires a maintainer. In the event an309    extension author would like to move beyond the project, the project should310    find a new maintainer including full source hosting transition and PyPI311    access.  If no maintainer is available, give access to the Flask core team.3121.  An approved Flask extension must provide exactly one package or module313    named ``flask_extensionname``.  They might also reside inside a314    ``flaskext`` namespace packages though this is discouraged now.3152.  It must ship a testing suite that can either be invoked with ``make test``316    or ``python setup.py test``.  For test suites invoked with ``make317    test`` the extension has to ensure that all dependencies for the test318    are installed automatically.  If tests are invoked with ``python setup.py319    test``, test dependencies can be specified in the `setup.py` file.  The320    test suite also has to be part of the distribution.3213.  APIs of approved extensions will be checked for the following322    characteristics:323324    -   an approved extension has to support multiple applications325        running in the same Python process.326    -   it must be possible to use the factory pattern for creating327        applications.3283294.  The license must be BSD/MIT/WTFPL licensed.3305.  The naming scheme for official extensions is *Flask-ExtensionName* or331    *ExtensionName-Flask*.3326.  Approved extensions must define all their dependencies in the333    `setup.py` file unless a dependency cannot be met because it is not334    available on PyPI.3357.  The extension must have documentation that uses one of the two Flask336    themes for Sphinx documentation.3378.  The setup.py description (and thus the PyPI description) has to338    link to the documentation, website (if there is one) and there339    must be a link to automatically install the development version340    (``PackageName==dev``).3419.  The ``zip_safe`` flag in the setup script must be set to ``False``,342    even if the extension would be safe for zipping.34310. An extension currently has to support Python 2.5, 2.6 as well as344    Python 2.7345346347.. _ext-import-transition:348349Extension Import Transition350---------------------------351352For a while we recommended using namespace packages for Flask extensions.353This turned out to be problematic in practice because many different354competing namespace package systems exist and pip would automatically355switch between different systems and this caused a lot of problems for356users.357358Instead we now recommend naming packages ``flask_foo`` instead of the now359deprecated ``flaskext.foo``.  Flask 0.8 introduces a redirect import360system that lets uses import from ``flask.ext.foo`` and it will try361``flask_foo`` first and if that fails ``flaskext.foo``.362363Flask extensions should urge users to import from ``flask.ext.foo``364instead of ``flask_foo`` or ``flaskext_foo`` so that extensions can365transition to the new package name without affecting users.366367368.. _OAuth extension: http://packages.python.org/Flask-OAuth/369.. _mailinglist: http://flask.pocoo.org/mailinglist/370.. _IRC channel: http://flask.pocoo.org/community/irc/