Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

345 lines · 13.1 KiB

Last changed by

Merge pull request #2709 from davidism/docs-themeDavid Lordbefore adoption5fba092

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 license45in order to be listed 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.150151When designing your classes, it's important to make them easily reusable152at the module level. This means the object itself must not under any153circumstances store any application specific state and must be shareable154between different applications.155156The Extension Code157------------------158159Here's the contents of the `flask_sqlite3.py` for copy/paste::160161    import sqlite3162    from flask import current_app, _app_ctx_stack163164165    class SQLite3(object):166        def __init__(self, app=None):167            self.app = app168            if app is not None:169                self.init_app(app)170171        def init_app(self, app):172            app.config.setdefault('SQLITE3_DATABASE', ':memory:')173            app.teardown_appcontext(self.teardown)174175        def connect(self):176            return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])177178        def teardown(self, exception):179            ctx = _app_ctx_stack.top180            if hasattr(ctx, 'sqlite3_db'):181                ctx.sqlite3_db.close()182183        @property184        def connection(self):185            ctx = _app_ctx_stack.top186            if ctx is not None:187                if not hasattr(ctx, 'sqlite3_db'):188                    ctx.sqlite3_db = self.connect()189                return ctx.sqlite3_db190191192So here's what these lines of code do:1931941.  The ``__init__`` method takes an optional app object and, if supplied, will195    call ``init_app``.1962.  The ``init_app`` method exists so that the ``SQLite3`` object can be197    instantiated without requiring an app object.  This method supports the198    factory pattern for creating applications.  The ``init_app`` will set the199    configuration for the database, defaulting to an in memory database if200    no configuration is supplied.  In addition, the ``init_app`` method attaches201    the ``teardown`` handler.2023.  Next, we define a ``connect`` method that opens a database connection.2034.  Finally, we add a ``connection`` property that on first access opens204    the database connection and stores it on the context.  This is also205    the recommended way to handling resources: fetch resources lazily the206    first time they are used.207208    Note here that we're attaching our database connection to the top209    application context via ``_app_ctx_stack.top``. Extensions should use210    the top context for storing their own information with a sufficiently211    complex name.212213So why did we decide on a class-based approach here?  Because using our214extension looks something like this::215216    from flask import Flask217    from flask_sqlite3 import SQLite3218219    app = Flask(__name__)220    app.config.from_pyfile('the-config.cfg')221    db = SQLite3(app)222223You can then use the database from views like this::224225    @app.route('/')226    def show_all():227        cur = db.connection.cursor()228        cur.execute(...)229230Likewise if you are outside of a request you can use the database by231pushing an app context::232233    with app.app_context():234        cur = db.connection.cursor()235        cur.execute(...)236237At the end of the ``with`` block the teardown handles will be executed238automatically.239240Additionally, the ``init_app`` method is used to support the factory pattern241for creating apps::242243    db = Sqlite3()244    # Then later on.245    app = create_app('the-config.cfg')246    db.init_app(app)247248Keep in mind that supporting this factory pattern for creating apps is required249for approved flask extensions (described below).250251.. admonition:: Note on ``init_app``252253   As you noticed, ``init_app`` does not assign ``app`` to ``self``.  This254   is intentional!  Class based Flask extensions must only store the255   application on the object when the application was passed to the256   constructor.  This tells the extension: I am not interested in using257   multiple applications.258259   When the extension needs to find the current application and it does260   not have a reference to it, it must either use the261   :data:`~flask.current_app` context local or change the API in a way262   that you can pass the application explicitly.263264265Using _app_ctx_stack266--------------------267268In the example above, before every request, a ``sqlite3_db`` variable is269assigned to ``_app_ctx_stack.top``.  In a view function, this variable is270accessible using the ``connection`` property of ``SQLite3``.  During the271teardown of a request, the ``sqlite3_db`` connection is closed.  By using272this pattern, the *same* connection to the sqlite3 database is accessible273to anything that needs it for the duration of the request.274275276Learn from Others277-----------------278279This documentation only touches the bare minimum for extension280development.  If you want to learn more, it's a very good idea to check281out existing extensions on the `Flask Extension Registry`_.  If you feel282lost there is still the `mailinglist`_ and the `IRC channel`_ to get some283ideas for nice looking APIs.  Especially if you do something nobody before284you did, it might be a very good idea to get some more input.  This not only285generates useful feedback on what people might want from an extension, but286also avoids having multiple developers working in isolation on pretty much the287same problem.288289Remember: good API design is hard, so introduce your project on the290mailinglist, and let other developers give you a helping hand with291designing the API.292293The best Flask extensions are extensions that share common idioms for the294API.  And this can only work if collaboration happens early.295296Approved Extensions297-------------------298299Flask also has the concept of approved extensions.  Approved extensions300are tested as part of Flask itself to ensure extensions do not break on301new releases.  These approved extensions are listed on the `Flask302Extension Registry`_ and marked appropriately.  If you want your own303extension to be approved you have to follow these guidelines:3043050.  An approved Flask extension requires a maintainer. In the event an306    extension author would like to move beyond the project, the project should307    find a new maintainer including full source hosting transition and PyPI308    access.  If no maintainer is available, give access to the Flask core team.3091.  An approved Flask extension must provide exactly one package or module310    named ``flask_extensionname``.3112.  It must ship a testing suite that can either be invoked with ``make test``312    or ``python setup.py test``.  For test suites invoked with ``make313    test`` the extension has to ensure that all dependencies for the test314    are installed automatically.  If tests are invoked with ``python setup.py315    test``, test dependencies can be specified in the :file:`setup.py` file.  The316    test suite also has to be part of the distribution.3173.  APIs of approved extensions will be checked for the following318    characteristics:319320   -   an approved extension has to support multiple applications321       running in the same Python process.322   -   it must be possible to use the factory pattern for creating323       applications.3243254.  The license must be BSD/MIT/WTFPL licensed.3265.  The naming scheme for official extensions is *Flask-ExtensionName* or327    *ExtensionName-Flask*.3286.  Approved extensions must define all their dependencies in the329    :file:`setup.py` file unless a dependency cannot be met because it is not330    available on PyPI.3317.  The documentation must use the ``flask`` theme from the `Official332    Pallets Themes`_.3338.  The setup.py description (and thus the PyPI description) has to334    link to the documentation, website (if there is one) and there335    must be a link to automatically install the development version336    (``PackageName==dev``).3379. The ``zip_safe`` flag in the setup script must be set to ``False``,338   even if the extension would be safe for zipping.33910. An extension currently has to support Python 3.4 and newer and 2.7.340341342.. _OAuth extension: https://pythonhosted.org/Flask-OAuth/343.. _mailinglist: http://flask.pocoo.org/mailinglist/344.. _IRC channel: http://flask.pocoo.org/community/irc/345.. _Official Pallets Themes: https://pypi.org/project/pallets-sphinx-themes/