Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

410 lines · 15.8 KiB

Last changed by

Do not suggest deprecated flask.ext.*Adrian Moennichbefore adoption88111ae

History of this file

Take it

1.. _extension-dev:23Flask Extension Development4===========================56Flask, being a microframework, often requires some repetitive steps to get7a third party library working.  Because very often these steps could be8abstracted to support multiple projects the `Flask Extension Registry`_9was created.1011If you want to create your own Flask extension for something that does not12exist yet, this guide to extension development will help you get your13extension running in no time and to feel like users would expect your14extension to behave.1516.. _Flask Extension Registry: http://flask.pocoo.org/extensions/1718Anatomy of an Extension19-----------------------2021Extensions are all located in a package called ``flask_something``22where "something" is the name of the library you want to bridge.  So for23example if you plan to add support for a library named `simplexml` to24Flask, you would name your extension's package ``flask_simplexml``.2526The name of the actual extension (the human readable name) however would27be something like "Flask-SimpleXML".  Make sure to include the name28"Flask" somewhere in that name and that you check the capitalization.29This is how users can then register dependencies to your extension in30their :file:`setup.py` files.3132But what do extensions look like themselves?  An extension has to ensure33that it works with multiple Flask application instances at once.  This is34a requirement because many people will use patterns like the35:ref:`app-factories` pattern to create their application as needed to aid36unittests and to support multiple configurations.  Because of that it is37crucial that your application supports that kind of behavior.3839Most importantly the extension must be shipped with a :file:`setup.py` file and40registered on PyPI.  Also the development checkout link should work so41that people can easily install the development version into their42virtualenv without having to download the library by hand.4344Flask extensions must be licensed under a BSD, MIT or more liberal license45to be able to be enlisted in the Flask Extension Registry.  Keep in mind46that the Flask Extension Registry is a moderated place and libraries will47be reviewed upfront if they behave as required.4849"Hello Flaskext!"50-----------------5152So let's get started with creating such a Flask extension.  The extension53we want to create here will provide very basic support for SQLite3.5455First we create the following folder structure::5657    flask-sqlite3/58        flask_sqlite3.py59        LICENSE60        README6162Here's the contents of the most important files:6364setup.py65````````6667The next file that is absolutely required is the :file:`setup.py` file which is68used to install your Flask extension.  The following contents are69something you can work with::7071    """72    Flask-SQLite373    -------------7475    This is the description for that library76    """77    from setuptools import setup787980    setup(81        name='Flask-SQLite3',82        version='1.0',83        url='http://example.com/flask-sqlite3/',84        license='BSD',85        author='Your Name',86        author_email='your-email@example.com',87        description='Very short description',88        long_description=__doc__,89        py_modules=['flask_sqlite3'],90        # if you would be using a package instead use packages instead91        # of py_modules:92        # packages=['flask_sqlite3'],93        zip_safe=False,94        include_package_data=True,95        platforms='any',96        install_requires=[97            'Flask'98        ],99        classifiers=[100            'Environment :: Web Environment',101            'Intended Audience :: Developers',102            'License :: OSI Approved :: BSD License',103            'Operating System :: OS Independent',104            'Programming Language :: Python',105            'Topic :: Internet :: WWW/HTTP :: Dynamic Content',106            'Topic :: Software Development :: Libraries :: Python Modules'107        ]108    )109110That's a lot of code but you can really just copy/paste that from existing111extensions and adapt.112113flask_sqlite3.py114````````````````115116Now this is where your extension code goes.  But how exactly should such117an extension look like?  What are the best practices?  Continue reading118for some insight.119120Initializing Extensions121-----------------------122123Many extensions will need some kind of initialization step.  For example,124consider an application that's currently connecting to SQLite like the125documentation suggests (:ref:`sqlite3`).  So how does the extension126know the name of the application object?127128Quite simple: you pass it to it.129130There are two recommended ways for an extension to initialize:131132initialization functions:133134    If your extension is called `helloworld` you might have a function135    called ``init_helloworld(app[, extra_args])`` that initializes the136    extension for that application.  It could attach before / after137    handlers etc.138139classes:140141    Classes work mostly like initialization functions but can later be142    used to further change the behavior.  For an example look at how the143    `OAuth extension`_ works: there is an `OAuth` object that provides144    some helper functions like `OAuth.remote_app` to create a reference to145    a remote application that uses OAuth.146147What to use depends on what you have in mind.  For the SQLite 3 extension148we will use the class-based approach because it will provide users with an149object that handles opening and closing database connections.150151What's important about classes is that they encourage to be shared around152on module level.  In that case, the object itself must not under any153circumstances store any application specific state and must be shareable154between different application.155156The Extension Code157------------------158159Here's the contents of the `flask_sqlite3.py` for copy/paste::160161    import sqlite3162    from flask import current_app163164    # Find the stack on which we want to store the database connection.165    # Starting with Flask 0.9, the _app_ctx_stack is the correct one,166    # before that we need to use the _request_ctx_stack.167    try:168        from flask import _app_ctx_stack as stack169    except ImportError:170        from flask import _request_ctx_stack as stack171172173    class SQLite3(object):174175        def __init__(self, app=None):176            self.app = app177            if app is not None:178                self.init_app(app)179180        def init_app(self, app):181            app.config.setdefault('SQLITE3_DATABASE', ':memory:')182            # Use the newstyle teardown_appcontext if it's available,183            # otherwise fall back to the request context184            if hasattr(app, 'teardown_appcontext'):185                app.teardown_appcontext(self.teardown)186            else:187                app.teardown_request(self.teardown)188189        def connect(self):190            return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])191192        def teardown(self, exception):193            ctx = stack.top194            if hasattr(ctx, 'sqlite3_db'):195                ctx.sqlite3_db.close()196197        @property198        def connection(self):199            ctx = stack.top200            if ctx is not None:201                if not hasattr(ctx, 'sqlite3_db'):202                    ctx.sqlite3_db = self.connect()203                return ctx.sqlite3_db204205206So here's what these lines of code do:2072081.  The ``__init__`` method takes an optional app object and, if supplied, will209    call ``init_app``.2102.  The ``init_app`` method exists so that the ``SQLite3`` object can be211    instantiated without requiring an app object.  This method supports the212    factory pattern for creating applications.  The ``init_app`` will set the213    configuration for the database, defaulting to an in memory database if214    no configuration is supplied.  In addition, the ``init_app`` method attaches215    the ``teardown`` handler.  It will try to use the newstyle app context216    handler and if it does not exist, falls back to the request context217    one.2183.  Next, we define a ``connect`` method that opens a database connection.2194.  Finally, we add a ``connection`` property that on first access opens220    the database connection and stores it on the context.  This is also221    the recommended way to handling resources: fetch resources lazily the222    first time they are used.223224    Note here that we're attaching our database connection to the top225    application context via ``_app_ctx_stack.top``. Extensions should use226    the top context for storing their own information with a sufficiently227    complex name.  Note that we're falling back to the228    ``_request_ctx_stack.top`` if the application is using an older229    version of Flask that does not support it.230231So why did we decide on a class-based approach here?  Because using our232extension looks something like this::233234    from flask import Flask235    from flask_sqlite3 import SQLite3236237    app = Flask(__name__)238    app.config.from_pyfile('the-config.cfg')239    db = SQLite3(app)240241You can then use the database from views like this::242243    @app.route('/')244    def show_all():245        cur = db.connection.cursor()246        cur.execute(...)247248Likewise if you are outside of a request but you are using Flask 0.9 or249later with the app context support, you can use the database in the same250way::251252    with app.app_context():253        cur = db.connection.cursor()254        cur.execute(...)255256At the end of the ``with`` block the teardown handles will be executed257automatically.258259Additionally, the ``init_app`` method is used to support the factory pattern260for creating apps::261262    db = Sqlite3()263    # Then later on.264    app = create_app('the-config.cfg')265    db.init_app(app)266267Keep in mind that supporting this factory pattern for creating apps is required268for approved flask extensions (described below).269270.. admonition:: Note on ``init_app``271272   As you noticed, ``init_app`` does not assign ``app`` to ``self``.  This273   is intentional!  Class based Flask extensions must only store the274   application on the object when the application was passed to the275   constructor.  This tells the extension: I am not interested in using276   multiple applications.277278   When the extension needs to find the current application and it does279   not have a reference to it, it must either use the280   :data:`~flask.current_app` context local or change the API in a way281   that you can pass the application explicitly.282283284Using _app_ctx_stack285--------------------286287In the example above, before every request, a ``sqlite3_db`` variable is288assigned to ``_app_ctx_stack.top``.  In a view function, this variable is289accessible using the ``connection`` property of ``SQLite3``.  During the290teardown of a request, the ``sqlite3_db`` connection is closed.  By using291this pattern, the *same* connection to the sqlite3 database is accessible292to anything that needs it for the duration of the request.293294If the :data:`~flask._app_ctx_stack` does not exist because the user uses295an old version of Flask, it is recommended to fall back to296:data:`~flask._request_ctx_stack` which is bound to a request.297298Teardown Behavior299-----------------300301*This is only relevant if you want to support Flask 0.6 and older*302303Due to the change in Flask 0.7 regarding functions that are run at the end304of the request your extension will have to be extra careful there if it305wants to continue to support older versions of Flask.  The following306pattern is a good way to support both::307308    def close_connection(response):309        ctx = _request_ctx_stack.top310        ctx.sqlite3_db.close()311        return response312313    if hasattr(app, 'teardown_request'):314        app.teardown_request(close_connection)315    else:316        app.after_request(close_connection)317318Strictly speaking the above code is wrong, because teardown functions are319passed the exception and typically don't return anything.  However because320the return value is discarded this will just work assuming that the code321in between does not touch the passed parameter.322323Learn from Others324-----------------325326This documentation only touches the bare minimum for extension327development.  If you want to learn more, it's a very good idea to check328out existing extensions on the `Flask Extension Registry`_.  If you feel329lost there is still the `mailinglist`_ and the `IRC channel`_ to get some330ideas for nice looking APIs.  Especially if you do something nobody before331you did, it might be a very good idea to get some more input.  This not332only to get an idea about what people might want to have from an333extension, but also to avoid having multiple developers working on pretty334much the same side by side.335336Remember: good API design is hard, so introduce your project on the337mailinglist, and let other developers give you a helping hand with338designing the API.339340The best Flask extensions are extensions that share common idioms for the341API.  And this can only work if collaboration happens early.342343Approved Extensions344-------------------345346Flask also has the concept of approved extensions.  Approved extensions347are tested as part of Flask itself to ensure extensions do not break on348new releases.  These approved extensions are listed on the `Flask349Extension Registry`_ and marked appropriately.  If you want your own350extension to be approved you have to follow these guidelines:3513520.  An approved Flask extension requires a maintainer. In the event an353    extension author would like to move beyond the project, the project should354    find a new maintainer including full source hosting transition and PyPI355    access.  If no maintainer is available, give access to the Flask core team.3561.  An approved Flask extension must provide exactly one package or module357    named ``flask_extensionname``.3582.  It must ship a testing suite that can either be invoked with ``make test``359    or ``python setup.py test``.  For test suites invoked with ``make360    test`` the extension has to ensure that all dependencies for the test361    are installed automatically.  If tests are invoked with ``python setup.py362    test``, test dependencies can be specified in the :file:`setup.py` file.  The363    test suite also has to be part of the distribution.3643.  APIs of approved extensions will be checked for the following365    characteristics:366367    -   an approved extension has to support multiple applications368        running in the same Python process.369    -   it must be possible to use the factory pattern for creating370        applications.3713724.  The license must be BSD/MIT/WTFPL licensed.3735.  The naming scheme for official extensions is *Flask-ExtensionName* or374    *ExtensionName-Flask*.3756.  Approved extensions must define all their dependencies in the376    :file:`setup.py` file unless a dependency cannot be met because it is not377    available on PyPI.3787.  The extension must have documentation that uses one of the two Flask379    themes for Sphinx documentation.3808.  The setup.py description (and thus the PyPI description) has to381    link to the documentation, website (if there is one) and there382    must be a link to automatically install the development version383    (``PackageName==dev``).3849.  The ``zip_safe`` flag in the setup script must be set to ``False``,385    even if the extension would be safe for zipping.38610. An extension currently has to support Python 2.6 as well as387    Python 2.7388389390Extension Import Transition391---------------------------392393In early versions of Flask we recommended using namespace packages for Flask394extensions, of the form ``flaskext.foo``. This turned out to be problematic in395practice because it meant that multiple ``flaskext`` packages coexist.396Consequently we have recommended to name extensions ``flask_foo`` over397``flaskext.foo`` for a long time.398399Flask 0.8 introduced a redirect import system as a compatibility aid for app400developers: Importing ``flask.ext.foo`` would try ``flask_foo`` and401``flaskext.foo`` in that order.402403As of Flask 0.11, most Flask extensions have transitioned to the new naming404schema. The ``flask.ext.foo`` compatibility alias is still in Flask 0.11 but is405now deprecated -- you should use ``flask_foo``.406407408.. _OAuth extension: http://pythonhosted.org/Flask-OAuth/409.. _mailinglist: http://flask.pocoo.org/mailinglist/410.. _IRC channel: http://flask.pocoo.org/community/irc/