Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

420 lines · 16.2 KiB

Last changed by

Merge pull request #731 from ThomasWaldmann/docsDaniel Neuhäuserbefore adoptionc87735f

History of this file

Take it

The walk stopped after 200 commits: lines older than 820d099 point at it.

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 1–2why, one step back
1.. _extension-dev:
2

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 3–42why, one step back
3Flask Extension Development
4===========================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 `setup.py` files.3132Flask sets up a redirect package called :data:`flask.ext` where users33should import the extensions from. If you for instance have a package34called ``flask_something`` users would import it as35``flask.ext.something``. This is done to transition from the old36namespace packages. See :ref:`ext-import-transition` for more details.3738But how do extensions look like themselves? An extension has to ensure39that it works with multiple Flask application instances at once. This is40a requirement because many people will use patterns like the41:ref:`app-factories` pattern to create their application as needed to aid42unittests and to support multiple configurations. Because of that it is

Use American English for "behavior" in docs.Ron DuPlainbefore adoptiona3cb2a3

line 43why, one step back
43crucial that your application supports that kind of behavior.

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 44–49why, one step back
44
45Most importantly the extension must be shipped with a `setup.py` file and46registered on PyPI. Also the development checkout link should work so47that people can easily install the development version into their48virtualenv without having to download the library by hand.49

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption2e816f5

lines 50–53why, one step back
50Flask extensions must be licensed under a BSD, MIT or more liberal license
51to be able to be enlisted in the Flask Extension Registry. Keep in mind52that the Flask Extension Registry is a moderated place and libraries will53be reviewed upfront if they behave as required.

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 54–129why, one step back
54
55"Hello Flaskext!"56-----------------5758So let's get started with creating such a Flask extension. The extension59we want to create here will provide very basic support for SQLite3.6061First we create the following folder structure::6263 flask-sqlite3/64 flask_sqlite3.py65 LICENSE66 README6768Here's the contents of the most important files:6970setup.py71````````7273The next file that is absolutely required is the `setup.py` file which is74used to install your Flask extension. The following contents are75something you can work with::7677 """78 Flask-SQLite379 -------------8081 This is the description for that library82 """83 from setuptools import setup848586 setup(87 name='Flask-SQLite3',88 version='1.0',89 url='http://example.com/flask-sqlite3/',90 license='BSD',91 author='Your Name',92 author_email='your-email@example.com',93 description='Very short description',94 long_description=__doc__,95 py_modules=['flask_sqlite3'],96 # if you would be using a package instead use packages instead97 # of py_modules:98 # packages=['flask_sqlite3'],99 zip_safe=False,100 include_package_data=True,101 platforms='any',102 install_requires=[103 'Flask'104 ],105 classifiers=[106 'Environment :: Web Environment',107 'Intended Audience :: Developers',108 'License :: OSI Approved :: BSD License',109 'Operating System :: OS Independent',110 'Programming Language :: Python',111 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',112 'Topic :: Software Development :: Libraries :: Python Modules'113 ]114 )115116That's a lot of code but you can really just copy/paste that from existing117extensions and adapt.118119flask_sqlite3.py120````````````````121122Now this is where your extension code goes. But how exactly should such123an extension look like? What are the best practices? Continue reading124for some insight.125126Initializing Extensions127-----------------------128129Many extensions will need some kind of initialization step. For example,

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 130–131why, one step back
130consider an application that's currently connecting to SQLite like the
131documentation suggests (:ref:`sqlite3`). So how does the extension

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 132–138why, one step back
132know the name of the application object?
133134Quite simple: you pass it to it.135136There are two recommended ways for an extension to initialize:137138initialization functions:

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 139why, one step back
139

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 140–145why, one step back
140 If your extension is called `helloworld` you might have a function
141 called ``init_helloworld(app[, extra_args])`` that initializes the142 extension for that application. It could attach before / after143 handlers etc.144145classes:

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 146why, one step back
146

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 147why, one step back
147 Classes work mostly like initialization functions but can later be

Use American English for "behavior" in docs.Ron DuPlainbefore adoptiona3cb2a3

line 148why, one step back
148 used to further change the behavior. For an example look at how the

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 149–153why, one step back
149 `OAuth extension`_ works: there is an `OAuth` object that provides
150 some helper functions like `OAuth.remote_app` to create a reference to151 a remote application that uses OAuth.152153What to use depends on what you have in mind. For the SQLite 3 extension

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 154–155why, one step back
154we will use the class-based approach because it will provide users with an
155object that handles opening and closing database connections.

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 156why, one step back
156

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 157–161why, one step back
157What's important about classes is that they encourage to be shared around
158on module level. In that case, the object itself must not under any159circumstances store any application specific state and must be shareable160between different application.161

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 162–167why, one step back
162The Extension Code
163------------------164165Here's the contents of the `flask_sqlite3.py` for copy/paste::166167 import sqlite3

Merge pull request #653 from methane/patch-1Armin Ronacherbefore adoptiondfdbc00

line 168why, one step back
168 from flask import current_app

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 169why, one step back
169

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 170–176why, one step back
170 # Find the stack on which we want to store the database connection.
171 # Starting with Flask 0.9, the _app_ctx_stack is the correct one,172 # before that we need to use the _request_ctx_stack.173 try:174 from flask import _app_ctx_stack as stack175 except ImportError:176 from flask import _request_ctx_stack as stack

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 177why, one step back
177

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 178why, one step back
178

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 179–180why, one step back
179 class SQLite3(object):
180

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 181why, one step back
181 def __init__(self, app=None):

Merge pull request #653 from methane/patch-1Armin Ronacherbefore adoptiondfdbc00

line 182why, one step back
182 self.app = app

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 183why, one step back
183 if app is not None:

Merge pull request #653 from methane/patch-1Armin Ronacherbefore adoptiondfdbc00

line 184why, one step back
184 self.init_app(app)

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 185–186why, one step back
185
186 def init_app(self, app):

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 187–193why, one step back
187 app.config.setdefault('SQLITE3_DATABASE', ':memory:')
188 # Use the newstyle teardown_appcontext if it's available,189 # otherwise fall back to the request context190 if hasattr(app, 'teardown_appcontext'):191 app.teardown_appcontext(self.teardown)192 else:193 app.teardown_request(self.teardown)

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 194–195why, one step back
194
195 def connect(self):

Merge pull request #653 from methane/patch-1Armin Ronacherbefore adoptiondfdbc00

line 196why, one step back
196 return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 197why, one step back
197

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 198–201why, one step back
198 def teardown(self, exception):
199 ctx = stack.top200 if hasattr(ctx, 'sqlite3_db'):201 ctx.sqlite3_db.close()

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 202why, one step back
202

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 203–204why, one step back
203 @property
204 def connection(self):

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

line 205why, one step back
205 ctx = stack.top

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 206why, one step back
206 if ctx is not None:

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 207–208why, one step back
207 if not hasattr(ctx, 'sqlite3_db'):
208 ctx.sqlite3_db = self.connect()

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 209–210why, one step back
209 return ctx.sqlite3_db
210

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 211why, one step back
211

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 212–213why, one step back
212So here's what these lines of code do:
213

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 214–220why, one step back
2141. The ``__init__`` method takes an optional app object and, if supplied, will
215 call ``init_app``.2162. The ``init_app`` method exists so that the ``SQLite3`` object can be217 instantiated without requiring an app object. This method supports the218 factory pattern for creating applications. The ``init_app`` will set the219 configuration for the database, defaulting to an in memory database if220 no configuration is supplied. In addition, the ``init_app`` method attaches

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 221–223why, one step back
221 the ``teardown`` handler. It will try to use the newstyle app context
222 handler and if it does not exist, falls back to the request context223 one.

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 224why, one step back
2243. Next, we define a ``connect`` method that opens a database connection.

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

line 225why, one step back
2254. Finally, we add a ``connection`` property that on first access opens

More documentation updates for 0.9Armin Ronacherbefore adoption52f9cef

lines 226–228why, one step back
226 the database connection and stores it on the context. This is also
227 the recommended way to handling resources: fetch resources lazily the228 first time they are used.

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 229why, one step back
229

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 230–236why, one step back
230 Note here that we're attaching our database connection to the top
231 application context via ``_app_ctx_stack.top``. Extensions should use232 the top context for storing their own information with a sufficiently233 complex name. Note that we're falling back to the234 ``_request_ctx_stack.top`` if the application is using an older235 version of Flask that does not support it.236

Merge pull request #392 from FND/docsRon DuPlainbefore adoption7ba5196

line 237why, one step back
237So why did we decide on a class-based approach here? Because using our

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 238–244why, one step back
238extension looks something like this::
239240 from flask import Flask241 from flask_sqlite3 import SQLite3242243 app = Flask(__name__)244 app.config.from_pyfile('the-config.cfg')

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 245why, one step back
245 db = SQLite3(app)

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 246–250why, one step back
246
247You can then use the database from views like this::248249 @app.route('/')250 def show_all():

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 251why, one step back
251 cur = db.connection.cursor()

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 252–253why, one step back
252 cur.execute(...)
253

Added an example for using the db connection without the requestArmin Ronacherbefore adoption32f845e

lines 254–264why, one step back
254Likewise if you are outside of a request but you are using Flask 0.9 or
255later with the app context support, you can use the database in the same256way::257258 with app.app_context():259 cur = db.connection.cursor()260 cur.execute(...)261262At the end of the `with` block the teardown handles will be executed263automatically.264

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 265–266why, one step back
265Additionally, the ``init_app`` method is used to support the factory pattern
266for creating apps::

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 267why, one step back
267

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 268–271why, one step back
268 db = Sqlite3()
269 # Then later on.270 app = create_app('the-config.cfg')271 db.init_app(app)

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 272why, one step back
272

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 273–274why, one step back
273Keep in mind that supporting this factory pattern for creating apps is required
274for approved flask extensions (described below).

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 275why, one step back
275

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

line 276why, one step back
276.. admonition:: Note on ``init_app``

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 277why, one step back
277

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 278–282why, one step back
278 As you noticed, ``init_app`` does not assign ``app`` to ``self``. This
279 is intentional! Class based Flask extensions must only store the280 application on the object when the application was passed to the281 constructor. This tells the extension: I am not interested in using282 multiple applications.

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

line 283why, one step back
283

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 284–287why, one step back
284 When the extension needs to find the current application and it does
285 not have a reference to it, it must either use the286 :data:`~flask.current_app` context local or change the API in a way287 that you can pass the application explicitly.

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 288–289why, one step back
288
289

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 290–308why, one step back
290Using _app_ctx_stack
291--------------------292293In the example above, before every request, a ``sqlite3_db`` variable is294assigned to ``_app_ctx_stack.top``. In a view function, this variable is295accessible using the ``connection`` property of ``SQLite3``. During the296teardown of a request, the ``sqlite3_db`` connection is closed. By using297this pattern, the *same* connection to the sqlite3 database is accessible298to anything that needs it for the duration of the request.299300If the :data:`~flask._app_ctx_stack` does not exist because the user uses301an old version of Flask, it is recommended to fall back to302:data:`~flask._request_ctx_stack` which is bound to a request.303304Teardown Behavior305-----------------306307*This is only relevant if you want to support Flask 0.6 and older*308

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 309–322why, one step back
309Due to the change in Flask 0.7 regarding functions that are run at the end
310of the request your extension will have to be extra careful there if it311wants to continue to support older versions of Flask. The following312pattern is a good way to support both::313314 def close_connection(response):315 ctx = _request_ctx_stack.top316 ctx.sqlite3_db.close()317 return response318319 if hasattr(app, 'teardown_request'):320 app.teardown_request(close_connection)321 else:322 app.after_request(close_connection)

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

line 323why, one step back
323

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 324–357why, one step back
324Strictly speaking the above code is wrong, because teardown functions are
325passed the exception and typically don't return anything. However because326the return value is discarded this will just work assuming that the code327in between does not touch the passed parameter.328329Learn from Others330-----------------331332This documentation only touches the bare minimum for extension333development. If you want to learn more, it's a very good idea to check334out existing extensions on the `Flask Extension Registry`_. If you feel335lost there is still the `mailinglist`_ and the `IRC channel`_ to get some336ideas for nice looking APIs. Especially if you do something nobody before337you did, it might be a very good idea to get some more input. This not338only to get an idea about what people might want to have from an339extension, but also to avoid having multiple developers working on pretty340much the same side by side.341342Remember: good API design is hard, so introduce your project on the343mailinglist, and let other developers give you a helping hand with344designing the API.345346The best Flask extensions are extensions that share common idioms for the347API. And this can only work if collaboration happens early.348349Approved Extensions350-------------------351352Flask also has the concept of approved extensions. Approved extensions353are tested as part of Flask itself to ensure extensions do not break on354new releases. These approved extensions are listed on the `Flask355Extension Registry`_ and marked appropriately. If you want your own356extension to be approved you have to follow these guidelines:357

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 358–361why, one step back
3580. An approved Flask extension requires a maintainer. In the event an
359 extension author would like to move beyond the project, the project should360 find a new maintainer including full source hosting transition and PyPI361 access. If no maintainer is available, give access to the Flask core team.

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 362–367why, one step back
3621. An approved Flask extension must provide exactly one package or module
363 named ``flask_extensionname``. They might also reside inside a364 ``flaskext`` namespace packages though this is discouraged now.3652. It must ship a testing suite that can either be invoked with ``make test``366 or ``python setup.py test``. For test suites invoked with ``make367 test`` the extension has to ensure that all dependencies for the test

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb

lines 368–370why, one step back
368 are installed automatically. If tests are invoked with ``python setup.py
369 test``, test dependencies can be specified in the `setup.py` file. The370 test suite also has to be part of the distribution.

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 371–392why, one step back
3713. APIs of approved extensions will be checked for the following
372 characteristics:373374 - an approved extension has to support multiple applications375 running in the same Python process.376 - it must be possible to use the factory pattern for creating377 applications.3783794. The license must be BSD/MIT/WTFPL licensed.3805. The naming scheme for official extensions is *Flask-ExtensionName* or381 *ExtensionName-Flask*.3826. Approved extensions must define all their dependencies in the383 `setup.py` file unless a dependency cannot be met because it is not384 available on PyPI.3857. The extension must have documentation that uses one of the two Flask386 themes for Sphinx documentation.3878. The setup.py description (and thus the PyPI description) has to388 link to the documentation, website (if there is one) and there389 must be a link to automatically install the development version390 (``PackageName==dev``).3919. The ``zip_safe`` flag in the setup script must be set to ``False``,392 even if the extension would be safe for zipping.

Merge pull request #731 from ThomasWaldmann/docsDaniel Neuhäuserbefore adoptionc87735f

line 393why, one step back
39310. An extension currently has to support Python 2.6 as well as

Add tests for template filter methods/decorators.Ron DuPlainbefore adoption820d099

lines 394–420why, one step back
394 Python 2.7
395396397.. _ext-import-transition:398399Extension Import Transition400---------------------------401402For a while we recommended using namespace packages for Flask extensions.403This turned out to be problematic in practice because many different404competing namespace package systems exist and pip would automatically405switch between different systems and this caused a lot of problems for406users.407408Instead we now recommend naming packages ``flask_foo`` instead of the now409deprecated ``flaskext.foo``. Flask 0.8 introduces a redirect import410system that lets uses import from ``flask.ext.foo`` and it will try411``flask_foo`` first and if that fails ``flaskext.foo``.412413Flask extensions should urge users to import from ``flask.ext.foo``414instead of ``flask_foo`` or ``flaskext_foo`` so that extensions can415transition to the new package name without affecting users.416417418.. _OAuth extension: http://packages.python.org/Flask-OAuth/419.. _mailinglist: http://flask.pocoo.org/mailinglist/420.. _IRC channel: http://flask.pocoo.org/community/irc/