Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

370 lines · 14.1 KiB

Last changed by

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

History of this file

Take it

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

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 1–18why, one step back
1Flask Extension Development
2===========================34Flask, being a microframework, often requires some repetitive steps to get5a third party library working. Because very often these steps could be6abstracted to support multiple projects the `Flask Extension Registry`_7was created.89If you want to create your own Flask extension for something that does not10exist yet, this guide to extension development will help you get your11extension running in no time and to feel like users would expect your12extension to behave.1314.. _Flask Extension Registry: http://flask.pocoo.org/extensions/1516Anatomy of an Extension17-----------------------18

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

line 19why, one step back
19Extensions are all located in a package called ``flask_something``

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 20–21why, one step back
20where "something" is the name of the library you want to bridge. So for
21example if you plan to add support for a library named `simplexml` to

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

line 22why, one step back
22Flask, you would name your extension's package ``flask_simplexml``.

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 23–29why, one step back
23
24The name of the actual extension (the human readable name) however would25be something like "Flask-SimpleXML". Make sure to include the name26"Flask" somewhere in that name and that you check the capitalization.27This is how users can then register dependencies to your extension in28their `setup.py` files.29

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

lines 30–34why, one step back
30Flask sets up a redirect package called :data:`flask.ext` where users
31should import the extensions from. If you for instance have a package32called ``flask_something`` users would import it as33``flask.ext.something``. This is done to transition from the old34namespace packages. See :ref:`ext-import-transition` for more details.

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 35–61why, one step back
35
36But how do extensions look like themselves? An extension has to ensure37that it works with multiple Flask application instances at once. This is38a requirement because many people will use patterns like the39:ref:`app-factories` pattern to create their application as needed to aid40unittests and to support multiple configurations. Because of that it is41crucial that your application supports that kind of behaviour.4243Most importantly the extension must be shipped with a `setup.py` file and44registered on PyPI. Also the development checkout link should work so45that people can easily install the development version into their46virtualenv without having to download the library by hand.4748Flask extensions must be licensed as BSD or MIT or a more liberal license49to be enlisted on the Flask Extension Registry. Keep in mind that the50Flask Extension Registry is a moderated place and libraries will be51reviewed upfront if they behave as required.5253"Hello Flaskext!"54-----------------5556So let's get started with creating such a Flask extension. The extension57we want to create here will provide very basic support for SQLite3.5859First we create the following folder structure::6061 flask-sqlite3/

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

line 62why, one step back
62 flask_sqlite3.py

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

line 63why, one step back
63 LICENSE

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

line 64why, one step back
64 README

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 65–92why, one step back
65
66Here's the contents of the most important files:6768setup.py69````````7071The next file that is absolutely required is the `setup.py` file which is72used to install your Flask extension. The following contents are73something you can work with::7475 """76 Flask-SQLite377 -------------7879 This is the description for that library80 """81 from setuptools import setup828384 setup(85 name='Flask-SQLite3',86 version='1.0',87 url='http://example.com/flask-sqlite3/',88 license='BSD',89 author='Your Name',90 author_email='your-email@example.com',91 description='Very short description',92 long_description=__doc__,

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

lines 93–96why, one step back
93 py_modules=['flask_sqlite3'],
94 # if you would be using a package instead use packages instead95 # of py_modules:96 # packages=['flask_sqlite3'],

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

line 97why, one step back
97 zip_safe=False,

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

line 98why, one step back
98 include_package_data=True,

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 99–114why, one step back
99 platforms='any',
100 install_requires=[101 'Flask'102 ],103 classifiers=[104 'Environment :: Web Environment',105 'Intended Audience :: Developers',106 'License :: OSI Approved :: BSD License',107 'Operating System :: OS Independent',108 'Programming Language :: Python',109 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',110 'Topic :: Software Development :: Libraries :: Python Modules'111 ]112 )113114That's a lot of code but you can really just copy/paste that from existing

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

line 115why, one step back
115extensions and adapt.

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

line 116why, one step back
116

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

lines 117–118why, one step back
117flask_sqlite3.py
118````````````````

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 119–127why, one step back
119
120Now this is where your extension code goes. But how exactly should such121an extension look like? What are the best practices? Continue reading122for some insight.123124Initializing Extensions125-----------------------126127Many extensions will need some kind of initialization step. For example,

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

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

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

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

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

line 137why, one step back
137

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 138–143why, one step back
138 If your extension is called `helloworld` you might have a function
139 called ``init_helloworld(app[, extra_args])`` that initializes the140 extension for that application. It could attach before / after141 handlers etc.142143classes:

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

line 144why, one step back
144

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 145–151why, one step back
145 Classes work mostly like initialization functions but can later be
146 used to further change the behaviour. For an example look at how the147 `OAuth extension`_ works: there is an `OAuth` object that provides148 some helper functions like `OAuth.remote_app` to create a reference to149 a remote application that uses OAuth.150151What 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 152–153why, one step back
152we will use the class-based approach because it will provide users with an
153object that handles opening and closing database connections.

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 154–157why, one step back
154
155The Extension Code156------------------157

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

line 158why, one step back
158Here's the contents of the `flask_sqlite3.py` for copy/paste::

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 159–163why, one step back
159
160 import sqlite3161162 from flask import _request_ctx_stack163

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

line 164why, one step back
164

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 165–166why, one step back
165 class SQLite3(object):
166

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

lines 167–174why, one step back
167 def __init__(self, app=None):
168 if app is not None:169 self.app = app170 self.init_app(self.app)171 else:172 self.app = None173174 def init_app(self, app):

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 175–190why, one step back
175 self.app = app
176 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')177 self.app.teardown_request(self.teardown_request)178 self.app.before_request(self.before_request)179180 def connect(self):181 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])182183 def before_request(self):184 ctx = _request_ctx_stack.top185 ctx.sqlite3_db = self.connect()186187 def teardown_request(self, exception):188 ctx = _request_ctx_stack.top189 ctx.sqlite3_db.close()190

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

lines 191–192why, one step back
191 @property
192 def connection(self):

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 193–196why, one step back
193 ctx = _request_ctx_stack.top
194 if ctx is not None:195 return ctx.sqlite3_db196

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

line 197why, one step back
197

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

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

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

lines 200–208why, one step back
2001. The ``__init__`` method takes an optional app object and, if supplied, will
201 call ``init_app``.2022. The ``init_app`` method exists so that the ``SQLite3`` object can be203 instantiated without requiring an app object. This method supports the204 factory pattern for creating applications. The ``init_app`` will set the205 configuration for the database, defaulting to an in memory database if206 no configuration is supplied. In addition, the ``init_app`` method attaches207 ``before_request`` and ``teardown_request`` handlers.2083. Next, we define a ``connect`` method that opens a database connection.

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 209–210why, one step back
2094. Then we set up the request handlers we bound to the app above. Note here
210 that we're attaching our database connection to the top request context via

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

lines 211–213why, one step back
211 ``_request_ctx_stack.top``. Extensions should use the top context and not the
212 ``g`` object to store things like database connections.2135. Finally, we add a ``connection`` property that simplifies access to the context's

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 214–215why, one step back
214 database.
215

Merge pull request #392 from FND/docsRon DuPlainbefore adoption7ba5196

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

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 217–219why, one step back
217extension looks something like this::
218219 from flask import Flask

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

line 220why, one step back
220 from flask_sqlite3 import SQLite3

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 221–223why, one step back
221
222 app = Flask(__name__)223 app.config.from_pyfile('the-config.cfg')

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

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

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 225–229why, one step back
225
226You can then use the database from views like this::227228 @app.route('/')229 def show_all():

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

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

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 231–232why, one step back
231 cur.execute(...)
232

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

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

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

line 235why, one step back
235

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

lines 236–239why, one step back
236 db = Sqlite3()
237 # Then later on.238 app = create_app('the-config.cfg')239 db.init_app(app)

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

line 240why, one step back
240

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

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

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 243–244why, one step back
243
244

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

lines 245–246why, one step back
245Using _request_ctx_stack
246------------------------

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

line 247why, one step back
247

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

lines 248–253why, one step back
248In the example above, before every request, a ``sqlite3_db`` variable is assigned
249to ``_request_ctx_stack.top``. In a view function, this variable is accessible250using the ``connection`` property of ``SQLite3``. During the teardown of a251request, the ``sqlite3_db`` connection is closed. By using this pattern, the252*same* connection to the sqlite3 database is accessible to anything that needs it253for the duration of the request.

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 254–272why, one step back
254
255End-Of-Request Behavior256-----------------------257258Due to the change in Flask 0.7 regarding functions that are run at the end259of the request your extension will have to be extra careful there if it260wants to continue to support older versions of Flask. The following261pattern is a good way to support both::262263 def close_connection(response):264 ctx = _request_ctx_stack.top265 ctx.sqlite3_db.close()266 return response267268 if hasattr(app, 'teardown_request'):269 app.teardown_request(close_connection)270 else:271 app.after_request(close_connection)272

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

line 273why, one step back
273

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 274–307why, one step back
274Strictly speaking the above code is wrong, because teardown functions are
275passed the exception and typically don't return anything. However because276the return value is discarded this will just work assuming that the code277in between does not touch the passed parameter.278279Learn from Others280-----------------281282This documentation only touches the bare minimum for extension283development. If you want to learn more, it's a very good idea to check284out existing extensions on the `Flask Extension Registry`_. If you feel285lost there is still the `mailinglist`_ and the `IRC channel`_ to get some286ideas for nice looking APIs. Especially if you do something nobody before287you did, it might be a very good idea to get some more input. This not288only to get an idea about what people might want to have from an289extension, but also to avoid having multiple developers working on pretty290much the same side by side.291292Remember: good API design is hard, so introduce your project on the293mailinglist, and let other developers give you a helping hand with294designing the API.295296The best Flask extensions are extensions that share common idioms for the297API. And this can only work if collaboration happens early.298299Approved Extensions300-------------------301302Flask also has the concept of approved extensions. Approved extensions303are tested as part of Flask itself to ensure extensions do not break on304new releases. These approved extensions are listed on the `Flask305Extension Registry`_ and marked appropriately. If you want your own306extension to be approved you have to follow these guidelines:307

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

lines 308–311why, one step back
3080. An approved Flask extension requires a maintainer. In the event an
309 extension author would like to move beyond the project, the project should310 find a new maintainer including full source hosting transition and PyPI311 access. If no maintainer is available, give access to the Flask core team.

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

line 312why, one step back
3121. An approved Flask extension must provide exactly one package or module

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

lines 313–314why, one step back
313 named ``flask_extensionname``. They might also reside inside a
314 ``flaskext`` namespace packages though this is discouraged now.

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 315–317why, one step back
3152. It must ship a testing suite that can either be invoked with ``make test``
316 or ``python setup.py test``. For test suites invoked with ``make317 test`` the extension has to ensure that all dependencies for the test

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

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

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 321–346why, one step back
3213. APIs of approved extensions will be checked for the following
322 characteristics:323324 - an approved extension has to support multiple applications325 running in the same Python process.326 - it must be possible to use the factory pattern for creating327 applications.3283294. The license must be BSD/MIT/WTFPL licensed.3305. The naming scheme for official extensions is *Flask-ExtensionName* or331 *ExtensionName-Flask*.3326. Approved extensions must define all their dependencies in the333 `setup.py` file unless a dependency cannot be met because it is not334 available on PyPI.3357. The extension must have documentation that uses one of the two Flask336 themes for Sphinx documentation.3378. The setup.py description (and thus the PyPI description) has to338 link to the documentation, website (if there is one) and there339 must be a link to automatically install the development version340 (``PackageName==dev``).3419. The ``zip_safe`` flag in the setup script must be set to ``False``,342 even if the extension would be safe for zipping.34310. An extension currently has to support Python 2.5, 2.6 as well as344 Python 2.7345346

Documented new import system for extensionsArmin Ronacherbefore adoption0719ad5

lines 347–367why, one step back
347.. _ext-import-transition:
348349Extension Import Transition350---------------------------351352For a while we recommended using namespace packages for Flask extensions.353This turned out to be problematic in practice because many different354competing namespace package systems exist and pip would automatically355switch between different systems and this caused a lot of problems for356users.357358Instead we now recommend naming packages ``flask_foo`` instead of the now359deprecated ``flaskext.foo``. Flask 0.8 introduces a redirect import360system that lets uses import from ``flask.ext.foo`` and it will try361``flask_foo`` first and if that fails ``flaskext.foo``.362363Flask extensions should urge users to import from ``flask.ext.foo``364instead of ``flask_foo`` or ``flaskext_foo`` so that extensions can365transition to the new package name without affecting users.366367

Merge pull request #288 from kennethreitz/patch-1Armin Ronacherbefore adoptionb34b086

lines 368–370why, one step back
368.. _OAuth extension: http://packages.python.org/Flask-OAuth/
369.. _mailinglist: http://flask.pocoo.org/mailinglist/370.. _IRC channel: http://flask.pocoo.org/community/irc/