Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

336 lines · 12.8 KiB

Last changed by

Merge pull request #3691 from greyli/update-discord-linksGrey Libefore adoptionf32f191

History of this file

Take it

1Flask Extension Development2===========================34Flask, being a microframework, often requires some repetitive steps to get5a third party library working. Many such extensions are already available6on `PyPI`_.78If you want to create your own Flask extension for something that does not9exist yet, this guide to extension development will help you get your10extension running in no time and to feel like users would expect your11extension to behave.1213Anatomy of an Extension14-----------------------1516Extensions are all located in a package called ``flask_something``17where "something" is the name of the library you want to bridge.  So for18example if you plan to add support for a library named `simplexml` to19Flask, you would name your extension's package ``flask_simplexml``.2021The name of the actual extension (the human readable name) however would22be something like "Flask-SimpleXML".  Make sure to include the name23"Flask" somewhere in that name and that you check the capitalization.24This is how users can then register dependencies to your extension in25their :file:`setup.py` files.2627But what do extensions look like themselves?  An extension has to ensure28that it works with multiple Flask application instances at once.  This is29a requirement because many people will use patterns like the30:doc:`/patterns/appfactories` pattern to create their application as31needed to aid unittests and to support multiple configurations. Because32of that it is crucial that your application supports that kind of33behavior.3435Most importantly the extension must be shipped with a :file:`setup.py` file and36registered on PyPI.  Also the development checkout link should work so37that people can easily install the development version into their38virtualenv without having to download the library by hand.3940Flask extensions must be licensed under a BSD, MIT or more liberal license41in order to be listed in the Flask Extension Registry.  Keep in mind42that the Flask Extension Registry is a moderated place and libraries will43be reviewed upfront if they behave as required.4445"Hello Flaskext!"46-----------------4748So let's get started with creating such a Flask extension.  The extension49we want to create here will provide very basic support for SQLite3.5051First we create the following folder structure::5253    flask-sqlite3/54        flask_sqlite3.py55        LICENSE56        README5758Here's the contents of the most important files:5960setup.py61````````6263The next file that is absolutely required is the :file:`setup.py` file which is64used to install your Flask extension.  The following contents are65something you can work with::6667    """68    Flask-SQLite369    -------------7071    This is the description for that library72    """73    from setuptools import setup747576    setup(77        name='Flask-SQLite3',78        version='1.0',79        url='http://example.com/flask-sqlite3/',80        license='BSD',81        author='Your Name',82        author_email='your-email@example.com',83        description='Very short description',84        long_description=__doc__,85        py_modules=['flask_sqlite3'],86        # if you would be using a package instead use packages instead87        # of py_modules:88        # packages=['flask_sqlite3'],89        zip_safe=False,90        include_package_data=True,91        platforms='any',92        install_requires=[93            'Flask'94        ],95        classifiers=[96            'Environment :: Web Environment',97            'Intended Audience :: Developers',98            'License :: OSI Approved :: BSD License',99            'Operating System :: OS Independent',100            'Programming Language :: Python',101            'Topic :: Internet :: WWW/HTTP :: Dynamic Content',102            'Topic :: Software Development :: Libraries :: Python Modules'103        ]104    )105106That's a lot of code but you can really just copy/paste that from existing107extensions and adapt.108109flask_sqlite3.py110````````````````111112Now this is where your extension code goes.  But how exactly should such113an extension look like?  What are the best practices?  Continue reading114for some insight.115116Initializing Extensions117-----------------------118119Many extensions will need some kind of initialization step.  For example,120consider an application that's currently connecting to SQLite like the121documentation suggests (:doc:`/patterns/sqlite3`). So how does the122extension know the name of the application object?123124Quite simple: you pass it to it.125126There are two recommended ways for an extension to initialize:127128initialization functions:129130    If your extension is called `helloworld` you might have a function131    called ``init_helloworld(app[, extra_args])`` that initializes the132    extension for that application.  It could attach before / after133    handlers etc.134135classes:136137    Classes work mostly like initialization functions but can later be138    used to further change the behavior.  For an example look at how the139    `OAuth extension`_ works: there is an `OAuth` object that provides140    some helper functions like `OAuth.remote_app` to create a reference to141    a remote application that uses OAuth.142143What to use depends on what you have in mind.  For the SQLite 3 extension144we will use the class-based approach because it will provide users with an145object that handles opening and closing database connections.146147When designing your classes, it's important to make them easily reusable148at the module level. This means the object itself must not under any149circumstances store any application specific state and must be shareable150between different applications.151152The Extension Code153------------------154155Here's the contents of the `flask_sqlite3.py` for copy/paste::156157    import sqlite3158    from flask import current_app, _app_ctx_stack159160161    class SQLite3(object):162        def __init__(self, app=None):163            self.app = app164            if app is not None:165                self.init_app(app)166167        def init_app(self, app):168            app.config.setdefault('SQLITE3_DATABASE', ':memory:')169            app.teardown_appcontext(self.teardown)170171        def connect(self):172            return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])173174        def teardown(self, exception):175            ctx = _app_ctx_stack.top176            if hasattr(ctx, 'sqlite3_db'):177                ctx.sqlite3_db.close()178179        @property180        def connection(self):181            ctx = _app_ctx_stack.top182            if ctx is not None:183                if not hasattr(ctx, 'sqlite3_db'):184                    ctx.sqlite3_db = self.connect()185                return ctx.sqlite3_db186187188So here's what these lines of code do:1891901.  The ``__init__`` method takes an optional app object and, if supplied, will191    call ``init_app``.1922.  The ``init_app`` method exists so that the ``SQLite3`` object can be193    instantiated without requiring an app object.  This method supports the194    factory pattern for creating applications.  The ``init_app`` will set the195    configuration for the database, defaulting to an in memory database if196    no configuration is supplied.  In addition, the ``init_app`` method197    attaches the ``teardown`` handler.1983.  Next, we define a ``connect`` method that opens a database connection.1994.  Finally, we add a ``connection`` property that on first access opens200    the database connection and stores it on the context.  This is also201    the recommended way to handling resources: fetch resources lazily the202    first time they are used.203204    Note here that we're attaching our database connection to the top205    application context via ``_app_ctx_stack.top``. Extensions should use206    the top context for storing their own information with a sufficiently207    complex name.208209So why did we decide on a class-based approach here?  Because using our210extension looks something like this::211212    from flask import Flask213    from flask_sqlite3 import SQLite3214215    app = Flask(__name__)216    app.config.from_pyfile('the-config.cfg')217    db = SQLite3(app)218219You can then use the database from views like this::220221    @app.route('/')222    def show_all():223        cur = db.connection.cursor()224        cur.execute(...)225226Likewise if you are outside of a request you can use the database by227pushing an app context::228229    with app.app_context():230        cur = db.connection.cursor()231        cur.execute(...)232233At the end of the ``with`` block the teardown handles will be executed234automatically.235236Additionally, the ``init_app`` method is used to support the factory pattern237for creating apps::238239    db = SQLite3()240    # Then later on.241    app = create_app('the-config.cfg')242    db.init_app(app)243244Keep in mind that supporting this factory pattern for creating apps is required245for approved flask extensions (described below).246247.. admonition:: Note on ``init_app``248249   As you noticed, ``init_app`` does not assign ``app`` to ``self``.  This250   is intentional!  Class based Flask extensions must only store the251   application on the object when the application was passed to the252   constructor.  This tells the extension: I am not interested in using253   multiple applications.254255   When the extension needs to find the current application and it does256   not have a reference to it, it must either use the257   :data:`~flask.current_app` context local or change the API in a way258   that you can pass the application explicitly.259260261Using _app_ctx_stack262--------------------263264In the example above, before every request, a ``sqlite3_db`` variable is265assigned to ``_app_ctx_stack.top``.  In a view function, this variable is266accessible using the ``connection`` property of ``SQLite3``.  During the267teardown of a request, the ``sqlite3_db`` connection is closed.  By using268this pattern, the *same* connection to the sqlite3 database is accessible269to anything that needs it for the duration of the request.270271272Learn from Others273-----------------274275This documentation only touches the bare minimum for extension development.276If you want to learn more, it's a very good idea to check out existing extensions277on the `PyPI`_.  If you feel lost there is still the `mailinglist`_ and the278`Discord server`_ to get some ideas for nice looking APIs.  Especially if you do279something nobody before you did, it might be a very good idea to get some more280input.  This not only generates useful feedback on what people might want from281an extension, but also avoids having multiple developers working in isolation282on pretty much the same problem.283284Remember: good API design is hard, so introduce your project on the285mailing list, and let other developers give you a helping hand with286designing the API.287288The best Flask extensions are extensions that share common idioms for the289API.  And this can only work if collaboration happens early.290291Approved Extensions292-------------------293294Flask previously had the concept of approved extensions. These came with295some vetting of support and compatibility. While this list became too296difficult to maintain over time, the guidelines are still relevant to297all extensions maintained and developed today, as they help the Flask298ecosystem remain consistent and compatible.2993000.  An approved Flask extension requires a maintainer. In the event an301    extension author would like to move beyond the project, the project302    should find a new maintainer and transfer access to the repository,303    documentation, PyPI, and any other services. If no maintainer304    is available, give access to the Pallets core team.3051.  The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*.306    It must provide exactly one package or module named307    ``flask_extension_name``.3082.  The extension must be BSD or MIT licensed. It must be open source309    and publicly available.3103.  The extension's API must have the following characteristics:311312    -   It must support multiple applications running in the same Python313        process. Use ``current_app`` instead of ``self.app``, store314        configuration and state per application instance.315    -   It must be possible to use the factory pattern for creating316        applications. Use the ``ext.init_app()`` pattern.3173184.  From a clone of the repository, an extension with its dependencies319    must be installable with ``pip install -e .``.3205.  It must ship a testing suite that can be invoked with ``tox -e py``321    or ``pytest``. If not using ``tox``, the test dependencies should be322    specified in a ``requirements.txt`` file. The tests must be part of323    the sdist distribution.3246.  The documentation must use the ``flask`` theme from the325    `Official Pallets Themes`_. A link to the documentation or project326    website must be in the PyPI metadata or the readme.3277.  For maximum compatibility, the extension should support the same328    versions of Python that Flask supports. 3.6+ is recommended as of329    2020. Use ``python_requires=">= 3.6"`` in ``setup.py`` to indicate330    supported versions.331332.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask333.. _OAuth extension: https://pythonhosted.org/Flask-OAuth/334.. _mailinglist: https://mail.python.org/mailman/listinfo/flask335.. _Discord server: https://discord.gg/pallets336.. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/