extensiondev.rst
This file
Path
docs/extensiondev.rst
383 lines · 14.1 KiB
Last changed by
Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18
History of this fileTake it
The walk stopped after 200 commits: lines older than 94f90bc point at it.
updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 1–166why, one step back1Flask Extension Development2===========================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-----------------------1819Extensions are all located in a package called ``flaskext.something``20where "something" is the name of the library you want to bridge. So for21example if you plan to add support for a library named `simplexml` to22Flask, you would name your extension's package ``flaskext.simplexml``.2324The 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.2930The magic that makes it possible to have your library in a package called31``flaskext.something`` is called a "namespace package". Check out the32guide below how to create something like that.3334But how do extensions look like themselves? An extension has to ensure35that it works with multiple Flask application instances at once. This is36a requirement because many people will use patterns like the37:ref:`app-factories` pattern to create their application as needed to aid38unittests and to support multiple configurations. Because of that it is39crucial that your application supports that kind of behaviour.4041Most importantly the extension must be shipped with a `setup.py` file and42registered on PyPI. Also the development checkout link should work so43that people can easily install the development version into their44virtualenv without having to download the library by hand.4546Flask extensions must be licensed as BSD or MIT or a more liberal license47to be enlisted on the Flask Extension Registry. Keep in mind that the48Flask Extension Registry is a moderated place and libraries will be49reviewed upfront if they behave as required.5051"Hello Flaskext!"52-----------------5354So let's get started with creating such a Flask extension. The extension55we want to create here will provide very basic support for SQLite3.5657There is a script on github called `Flask Extension Wizard`_ which helps58you create the initial folder structure. But for this very basic example59we want to create all by hand to get a better feeling for it.6061First we create the following folder structure::6263 flask-sqlite3/64 flaskext/65 __init__.py66 sqlite3.py67 setup.py68 LICENSE6970Here's the contents of the most important files:7172flaskext/__init__.py73````````````````````7475The only purpose of this file is to mark the package as namespace package.76This is required so that multiple modules from different PyPI packages can77reside in the same Python package::7879 __import__('pkg_resources').declare_namespace(__name__)8081If you want to know exactly what is happening there, checkout the82distribute or setuptools docs which explain how this works.8384Just make sure to not put anything else in there!8586setup.py87````````8889The next file that is absolutely required is the `setup.py` file which is90used to install your Flask extension. The following contents are91something you can work with::9293 """94 Flask-SQLite395 -------------9697 This is the description for that library98 """99 from setuptools import setup100101102 setup(103 name='Flask-SQLite3',104 version='1.0',105 url='http://example.com/flask-sqlite3/',106 license='BSD',107 author='Your Name',108 author_email='your-email@example.com',109 description='Very short description',110 long_description=__doc__,111 packages=['flaskext'],112 namespace_packages=['flaskext'],113 zip_safe=False,114 platforms='any',115 install_requires=[116 'Flask'117 ],118 classifiers=[119 'Environment :: Web Environment',120 'Intended Audience :: Developers',121 'License :: OSI Approved :: BSD License',122 'Operating System :: OS Independent',123 'Programming Language :: Python',124 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',125 'Topic :: Software Development :: Libraries :: Python Modules'126 ]127 )128129That's a lot of code but you can really just copy/paste that from existing130extensions and adapt. This is also what the wizard creates for you if you131use it.132133flaskext/sqlite3.py134```````````````````135136Now this is where your extension code goes. But how exactly should such137an extension look like? What are the best practices? Continue reading138for some insight.139140Initializing Extensions141-----------------------142143Many extensions will need some kind of initialization step. For example,144consider your application is currently connecting to SQLite like the145documentation suggests (:ref:`sqlite3`) you will need to provide a few146functions and before / after request handlers. So how does the extension147know the name of the application object?148149Quite simple: you pass it to it.150151There are two recommended ways for an extension to initialize:152153initialization functions:154 If your extension is called `helloworld` you might have a function155 called ``init_helloworld(app[, extra_args])`` that initializes the156 extension for that application. It could attach before / after157 handlers etc.158159classes:160 Classes work mostly like initialization functions but can later be161 used to further change the behaviour. For an example look at how the162 `OAuth extension`_ works: there is an `OAuth` object that provides163 some helper functions like `OAuth.remote_app` to create a reference to164 a remote application that uses OAuth.165166What to use depends on what you have in mind. For the SQLite 3 extensionMerge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 167–168why, one step back167we will use the class based approach because it will provide users with a168manager object that handles opening and closing database connections.updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 169–177why, one step back169170The Extension Code171------------------172173Here's the contents of the `flaskext/sqlite3.py` for copy/paste::174175 from __future__ import absolute_import176 import sqlite3177Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 178–179why, one step back178 from flask import _request_ctx_stack179updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 180why, one step back180 class SQLite3(object):Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
line 181why, one step back181updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 182–184why, one step back182 def __init__(self, app):183 self.app = app184 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18
line 185why, one step back185 self.app.teardown_request(self.teardown_request)Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
line 186why, one step back186 self.app.before_request(self.before_request)updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 187–191why, one step back187188 def connect(self):189 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])190191 def before_request(self):Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 192–193why, one step back192 ctx = _request_ctx_stack.top193 ctx.sqlite3_db = self.connect()updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 194why, one step back194Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18
line 195why, one step back195 def teardown_request(self, exception):Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 196–197why, one step back196 ctx = _request_ctx_stack.top197 ctx.sqlite3_db.close()updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 198why, one step back198Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 199–202why, one step back199 def get_db(self):200 ctx = _request_ctx_stack.top201 if ctx is not None:202 return ctx.sqlite3_dbupdated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 203why, one step back203Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
line 204why, one step back204So here's what these lines of code do:updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 205why, one step back205Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 206–212why, one step back2061. The ``__future__`` import is necessary to activate absolute imports.207 Otherwise we could not call our module `sqlite3.py` and import the208 top-level `sqlite3` module which actually implements the connection to209 SQLite.2102. We create a class for our extension that requires a supplied `app` object,211 sets a configuration for the database if it's not there212 (:meth:`dict.setdefault`), and attaches `before_request` andMerge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18
line 213why, one step back213 `teardown_request` handlers.Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 214–222why, one step back2143. Next, we define a `connect` function that opens a database connection.2154. Then we set up the request handlers we bound to the app above. Note here216 that we're attaching our database connection to the top request context via217 `_request_ctx_stack.top`. Extensions should use the top context and not the218 `g` object to store things like database connections.2195. Finally, we add a `get_db` function that simplifies access to the context's220 database.221222So why did we decide on a class based approach here? Because using ourupdated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 223–224why, one step back223extension looks something like this::224Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
line 225why, one step back225 from flask import Flaskupdated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 226–229why, one step back226 from flaskext.sqlite3 import SQLite3227228 app = Flask(__name__)229 app.config.from_pyfile('the-config.cfg')Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 230–231why, one step back230 manager = SQLite3(app)231 db = manager.get_db()updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 232why, one step back232Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
line 233why, one step back233You can then use the database from views like this::updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 234–236why, one step back234235 @app.route('/')236 def show_all():Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
line 237why, one step back237 cur = db.cursor()updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 238–239why, one step back238 cur.execute(...)239Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
line 240why, one step back240Opening a database connection from outside a view function is simple.updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 241–242why, one step back241242>>> from yourapplication import dbMerge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 243–244why, one step back243>>> cur = db.cursor()244>>> cur.execute(...)updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 245why, one step back245Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 246–247why, one step back246Adding an `init_app` Function247-----------------------------updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 248why, one step back248Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 249–252why, one step back249In practice, you'll almost always want to permit users to initialize your250extension and provide an app object after the fact. This can help avoid251circular import problems when a user is breaking their app into multiple files.252Our extension could add an `init_app` function as follows::updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 253why, one step back253Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
line 254why, one step back254 class SQLite3(object):updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 255why, one step back255Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 256–261why, one step back256 def __init__(self, app=None):257 if app is not None:258 self.app = app259 self.init_app(self.app)260 else:261 self.app = Noneupdated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 262why, one step back262Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 263–265why, one step back263 def init_app(self, app):264 self.app = app265 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18
line 266why, one step back266 self.app.teardown_request(self.teardown_request)Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
line 267why, one step back267 self.app.before_request(self.before_request)updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 268why, one step back268Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 269–270why, one step back269 def connect(self):270 return sqlite3.connect(app.config['SQLITE3_DATABASE'])updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 271why, one step back271Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 272–275why, one step back272 def before_request(self):273 ctx = _request_ctx_stack.top274 ctx.sqlite3_db = self.connect()275Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18
line 276why, one step back276 def teardown_request(self, exception):Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 277–278why, one step back277 ctx = _request_ctx_stack.top278 ctx.sqlite3_db.close()updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
line 279why, one step back279Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
lines 280–291why, one step back280 def get_db(self):281 ctx = _request_ctx_stack.top282 if ctx is not None:283 return ctx.sqlite3_db284285The user could then initialize the extension in one file::286287 manager = SQLite3()288289and bind their app to the extension in another file::290291 manager.init_app(app)Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18
lines 292–314why, one step back292293End-Of-Request Behavior294-----------------------295296Due to the change in Flask 0.7 regarding functions that are run at the end297of the request your extension will have to be extra careful there if it298wants to continue to support older versions of Flask. The following299pattern is a good way to support both::300301 def close_connection(response):302 ctx = _request_ctx_stack.top303 ctx.sqlite3_db.close()304 return response305306 if hasattr(app, 'teardown_request'):307 app.teardown_request(close_connection)308 else:309 app.after_request(close_connection)310311Strictly speaking the above code is wrong, because teardown functions are312passed the exception and typically don't return anything. However because313the return value is discarded this will just work assuming that the code314in between does not touch the passed parameter.Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c
line 315why, one step back315updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 316–346why, one step back316Learn from Others317-----------------318319This documentation only touches the bare minimum for extension320development. If you want to learn more, it's a very good idea to check321out existing extensions on the `Flask Extension Registry`_. If you feel322lost there is still the `mailinglist`_ and the `IRC channel`_ to get some323ideas for nice looking APIs. Especially if you do something nobody before324you did, it might be a very good idea to get some more input. This not325only to get an idea about what people might want to have from an326extension, but also to avoid having multiple developers working on pretty327much the same side by side.328329Remember: good API design is hard, so introduce your project on the330mailinglist, and let other developers give you a helping hand with331designing the API.332333The best Flask extensions are extensions that share common idioms for the334API. And this can only work if collaboration happens early.335336Approved Extensions337-------------------338339Flask also has the concept of approved extensions. Approved extensions340are tested as part of Flask itself to ensure extensions do not break on341new releases. These approved extensions are listed on the `Flask342Extension Registry`_ and marked appropriately. If you want your own343extension to be approved you have to follow these guidelines:3443451. An approved Flask extension must provide exactly one package or module346 inside the `flaskext` namespace package.Fixed some small typos in the documentation.Sam Andersonbefore adoptionda00160
lines 347–348why, one step back3472. It must ship a testing suite that can either be invoked with ``make test``348 or ``python setup.py test``. For test suites invoked with ``makeupdated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 349–351why, one step back349 test`` the extension has to ensure that all dependencies for the test350 are installed automatically, in case of ``python setup.py test``351 dependencies for tests alone can be specified in the `setup.py`Fixed some small typos in the documentation.Sam Andersonbefore adoptionda00160
line 352why, one step back352 file. The test suite also has to be part of the distribution.updated docs on FastCGI deployment with Lightyfmwbefore adoption94f90bc
lines 353–383why, one step back3533. APIs of approved extensions will be checked for the following354 characteristics:355356 - an approved extension has to support multiple applications357 running in the same Python process.358 - it must be possible to use the factory pattern for creating359 applications.3603614. The license must be BSD/MIT/WTFPL licensed.3625. The naming scheme for official extensions is *Flask-ExtensionName* or363 *ExtensionName-Flask*.3646. Approved extensions must define all their dependencies in the365 `setup.py` file unless a dependency cannot be met because it is not366 available on PyPI.3677. The extension must have documentation that uses one of the two Flask368 themes for Sphinx documentation.3698. The setup.py description (and thus the PyPI description) has to370 link to the documentation, website (if there is one) and there371 must be a link to automatically install the development version372 (``PackageName==dev``).3739. The ``zip_safe`` flag in the setup script must be set to ``False``,374 even if the extension would be safe for zipping.37510. An extension currently has to support Python 2.5, 2.6 as well as376 Python 2.7377378379.. _Flask Extension Wizard:380 http://github.com/mitsuhiko/flask-extension-wizard381.. _OAuth extension: http://packages.python.org/Flask-OAuth/382.. _mailinglist: http://flask.pocoo.org/mailinglist/383.. _IRC channel: http://flask.pocoo.org/community/irc/