extensiondev.rst
This file
Path
docs/extensiondev.rst
335 lines · 12.8 KiB
Last changed by
Merge branch '1.1.x'David Lordbefore adoption6429bf1
History of this fileTake 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:ref:`app-factories` pattern to create their application as needed to aid31unittests and to support multiple configurations. Because of that it is32crucial that your application supports that kind of behavior.3334Most importantly the extension must be shipped with a :file:`setup.py` file and35registered on PyPI. Also the development checkout link should work so36that people can easily install the development version into their37virtualenv without having to download the library by hand.3839Flask extensions must be licensed under a BSD, MIT or more liberal license40in order to be listed in the Flask Extension Registry. Keep in mind41that the Flask Extension Registry is a moderated place and libraries will42be reviewed upfront if they behave as required.4344"Hello Flaskext!"45-----------------4647So let's get started with creating such a Flask extension. The extension48we want to create here will provide very basic support for SQLite3.4950First we create the following folder structure::5152 flask-sqlite3/53 flask_sqlite3.py54 LICENSE55 README5657Here's the contents of the most important files:5859setup.py60````````6162The next file that is absolutely required is the :file:`setup.py` file which is63used to install your Flask extension. The following contents are64something you can work with::6566 """67 Flask-SQLite368 -------------6970 This is the description for that library71 """72 from setuptools import setup737475 setup(76 name='Flask-SQLite3',77 version='1.0',78 url='http://example.com/flask-sqlite3/',79 license='BSD',80 author='Your Name',81 author_email='your-email@example.com',82 description='Very short description',83 long_description=__doc__,84 py_modules=['flask_sqlite3'],85 # if you would be using a package instead use packages instead86 # of py_modules:87 # packages=['flask_sqlite3'],88 zip_safe=False,89 include_package_data=True,90 platforms='any',91 install_requires=[92 'Flask'93 ],94 classifiers=[95 'Environment :: Web Environment',96 'Intended Audience :: Developers',97 'License :: OSI Approved :: BSD License',98 'Operating System :: OS Independent',99 'Programming Language :: Python',100 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',101 'Topic :: Software Development :: Libraries :: Python Modules'102 ]103 )104105That's a lot of code but you can really just copy/paste that from existing106extensions and adapt.107108flask_sqlite3.py109````````````````110111Now this is where your extension code goes. But how exactly should such112an extension look like? What are the best practices? Continue reading113for some insight.114115Initializing Extensions116-----------------------117118Many extensions will need some kind of initialization step. For example,119consider an application that's currently connecting to SQLite like the120documentation suggests (:ref:`sqlite3`). So how does the extension121know the name of the application object?122123Quite simple: you pass it to it.124125There are two recommended ways for an extension to initialize:126127initialization functions:128129 If your extension is called `helloworld` you might have a function130 called ``init_helloworld(app[, extra_args])`` that initializes the131 extension for that application. It could attach before / after132 handlers etc.133134classes:135136 Classes work mostly like initialization functions but can later be137 used to further change the behavior. For an example look at how the138 `OAuth extension`_ works: there is an `OAuth` object that provides139 some helper functions like `OAuth.remote_app` to create a reference to140 a remote application that uses OAuth.141142What to use depends on what you have in mind. For the SQLite 3 extension143we will use the class-based approach because it will provide users with an144object that handles opening and closing database connections.145146When designing your classes, it's important to make them easily reusable147at the module level. This means the object itself must not under any148circumstances store any application specific state and must be shareable149between different applications.150151The Extension Code152------------------153154Here's the contents of the `flask_sqlite3.py` for copy/paste::155156 import sqlite3157 from flask import current_app, _app_ctx_stack158159160 class SQLite3(object):161 def __init__(self, app=None):162 self.app = app163 if app is not None:164 self.init_app(app)165166 def init_app(self, app):167 app.config.setdefault('SQLITE3_DATABASE', ':memory:')168 app.teardown_appcontext(self.teardown)169170 def connect(self):171 return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])172173 def teardown(self, exception):174 ctx = _app_ctx_stack.top175 if hasattr(ctx, 'sqlite3_db'):176 ctx.sqlite3_db.close()177178 @property179 def connection(self):180 ctx = _app_ctx_stack.top181 if ctx is not None:182 if not hasattr(ctx, 'sqlite3_db'):183 ctx.sqlite3_db = self.connect()184 return ctx.sqlite3_db185186187So here's what these lines of code do:1881891. The ``__init__`` method takes an optional app object and, if supplied, will190 call ``init_app``.1912. The ``init_app`` method exists so that the ``SQLite3`` object can be192 instantiated without requiring an app object. This method supports the193 factory pattern for creating applications. The ``init_app`` will set the194 configuration for the database, defaulting to an in memory database if195 no configuration is supplied. In addition, the ``init_app`` method196 attaches the ``teardown`` handler.1973. Next, we define a ``connect`` method that opens a database connection.1984. Finally, we add a ``connection`` property that on first access opens199 the database connection and stores it on the context. This is also200 the recommended way to handling resources: fetch resources lazily the201 first time they are used.202203 Note here that we're attaching our database connection to the top204 application context via ``_app_ctx_stack.top``. Extensions should use205 the top context for storing their own information with a sufficiently206 complex name.207208So why did we decide on a class-based approach here? Because using our209extension looks something like this::210211 from flask import Flask212 from flask_sqlite3 import SQLite3213214 app = Flask(__name__)215 app.config.from_pyfile('the-config.cfg')216 db = SQLite3(app)217218You can then use the database from views like this::219220 @app.route('/')221 def show_all():222 cur = db.connection.cursor()223 cur.execute(...)224225Likewise if you are outside of a request you can use the database by226pushing an app context::227228 with app.app_context():229 cur = db.connection.cursor()230 cur.execute(...)231232At the end of the ``with`` block the teardown handles will be executed233automatically.234235Additionally, the ``init_app`` method is used to support the factory pattern236for creating apps::237238 db = SQLite3()239 # Then later on.240 app = create_app('the-config.cfg')241 db.init_app(app)242243Keep in mind that supporting this factory pattern for creating apps is required244for approved flask extensions (described below).245246.. admonition:: Note on ``init_app``247248 As you noticed, ``init_app`` does not assign ``app`` to ``self``. This249 is intentional! Class based Flask extensions must only store the250 application on the object when the application was passed to the251 constructor. This tells the extension: I am not interested in using252 multiple applications.253254 When the extension needs to find the current application and it does255 not have a reference to it, it must either use the256 :data:`~flask.current_app` context local or change the API in a way257 that you can pass the application explicitly.258259260Using _app_ctx_stack261--------------------262263In the example above, before every request, a ``sqlite3_db`` variable is264assigned to ``_app_ctx_stack.top``. In a view function, this variable is265accessible using the ``connection`` property of ``SQLite3``. During the266teardown of a request, the ``sqlite3_db`` connection is closed. By using267this pattern, the *same* connection to the sqlite3 database is accessible268to anything that needs it for the duration of the request.269270271Learn from Others272-----------------273274This documentation only touches the bare minimum for extension development.275If you want to learn more, it's a very good idea to check out existing extensions276on the `PyPI`_. If you feel lost there is still the `mailinglist`_ and the277`Discord server`_ to get some ideas for nice looking APIs. Especially if you do278something nobody before you did, it might be a very good idea to get some more279input. This not only generates useful feedback on what people might want from280an extension, but also avoids having multiple developers working in isolation281on pretty much the same problem.282283Remember: good API design is hard, so introduce your project on the284mailing list, and let other developers give you a helping hand with285designing the API.286287The best Flask extensions are extensions that share common idioms for the288API. And this can only work if collaboration happens early.289290Approved Extensions291-------------------292293Flask previously had the concept of approved extensions. These came with294some vetting of support and compatibility. While this list became too295difficult to maintain over time, the guidelines are still relevant to296all extensions maintained and developed today, as they help the Flask297ecosystem remain consistent and compatible.2982990. An approved Flask extension requires a maintainer. In the event an300 extension author would like to move beyond the project, the project301 should find a new maintainer and transfer access to the repository,302 documentation, PyPI, and any other services. If no maintainer303 is available, give access to the Pallets core team.3041. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*.305 It must provide exactly one package or module named306 ``flask_extension_name``.3072. The extension must be BSD or MIT licensed. It must be open source308 and publicly available.3093. The extension's API must have the following characteristics:310311 - It must support multiple applications running in the same Python312 process. Use ``current_app`` instead of ``self.app``, store313 configuration and state per application instance.314 - It must be possible to use the factory pattern for creating315 applications. Use the ``ext.init_app()`` pattern.3163174. From a clone of the repository, an extension with its dependencies318 must be installable with ``pip install -e .``.3195. It must ship a testing suite that can be invoked with ``tox -e py``320 or ``pytest``. If not using ``tox``, the test dependencies should be321 specified in a ``requirements.txt`` file. The tests must be part of322 the sdist distribution.3236. The documentation must use the ``flask`` theme from the324 `Official Pallets Themes`_. A link to the documentation or project325 website must be in the PyPI metadata or the readme.3267. For maximum compatibility, the extension should support the same327 versions of Python that Flask supports. 3.6+ is recommended as of328 2020. Use ``python_requires=">= 3.6"`` in ``setup.py`` to indicate329 supported versions.330331.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask332.. _OAuth extension: https://pythonhosted.org/Flask-OAuth/333.. _mailinglist: https://mail.python.org/mailman/listinfo/flask334.. _Discord server: https://discord.gg/t6rrQZH335.. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/