extensiondev.rst
This file
Path
docs/extensiondev.rst
323 lines · 11.7 KiB
Last changed by
Approved extensions must not be GPLArmin Ronacherbefore adoptiona7d83a9
History of this fileTake it
Added document about extension developmentArmin Ronacherbefore adoptionee69fb5
lines 1–162why, 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 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.139140141Initializing Extensions142-----------------------143144Many extensions will need some kind of initialization step. For example,145consider your application is currently connecting to SQLite like the146documentation suggests (:ref:`sqlite3`) you will need to provide a few147functions and before / after request handlers. So how does the extension148know the name of the application object?149150Quite simple: you pass it to it.151152There are two recommended ways for an extension to initialize:153154initialization functions:155 If your extension is called `helloworld` you might have a function156 called ``init_helloworld(app[, extra_args])`` that initalizes the157 extension for that application. It could attach before / after158 handlers etc.159160classes:161 Classes work mostly like initialization functions but can later be162 used to further change the behaviour. For an example look at how theFix some typos in the docsjgraemebefore adoption540eca1
line 163why, one step back163 `OAuth extension`_ works: there is an `OAuth` object that providesAdded document about extension developmentArmin Ronacherbefore adoptionee69fb5
lines 164–224why, one step back164 some helper functions like `OAuth.remote_app` to create a reference to165 a remote application that uses OAuth.166167What to use depends on what you have in mind. For the SQLite 3 extension168we will need to use the class based approach because we have to use a169controller object that can be used to connect to the database.170171The Extension Code172------------------173174Here the contents of the `flaskext/sqlite3.py` for copy/paste::175176 from __future__ import absolute_import177 import sqlite3178 from flask import g179180 class SQLite3(object):181 182 def __init__(self, app):183 self.app = app184 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')185186 self.app.before_request(self.before_request)187 self.app.after_request(self.after_request)188189 def connect(self):190 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])191192 def before_request(self):193 g.sqlite3_db = self.connect()194195 def after_request(self, response):196 g.sqlite3_db.close()197 return response198199So here what the lines of code do:2002011. the ``__future__`` import is necessary to activate absolute imports.202 This is needed because otherwise we could not call our module203 `sqlite3.py` and import the top-level `sqlite3` module which actually204 implements the connection to SQLite.2052. We create a class for our extension that sets a default configuration206 for the SQLite 3 database if it's not there (:meth:`dict.setdefault`)207 and connects two functions as before and after request handlers.2083. Then it implements a `connect` function that returns a new database209 connection and the two handlers.210211So why did we decide on a class based approach here? Because using that212extension looks something like this::213214 from flask import Flask, g215 from flaskext.sqlite3 import SQLite3216217 app = Flask(__name__)218 app.config.from_pyfile('the-config.cfg')219 db = SQLite(app)220221Either way you can use the database from the views like this::222223 @app.route('/')224 def show_all():Typo in extension development docs.Simon Sapinbefore adoptione3de5e6
line 225why, one step back225 cur = g.sqlite3_db.cursor()Added document about extension developmentArmin Ronacherbefore adoptionee69fb5
lines 226–266why, one step back226 cur.execute(...)227228But how would you open a database connection from outside a view function?229This is where the `db` object now comes into play:230231>>> from yourapplication import db232>>> con = db.connect()233>>> cur = con.cursor()234235If you don't need that, you can go with initialization functions.236237Initialization Functions238------------------------239240Here how the module would look like with initialization functions::241242 from __future__ import absolute_import243 import sqlite3244 from flask import g245246 def init_sqlite3(app):247 app = app248 app.config.setdefault('SQLITE3_DATABASE', ':memory:')249250 @app.before_request251 def before_request():252 g.sqlite3_db = sqlite3.connect(self.app.config['SQLITE3_DATABASE'])253254 @app.after_request255 def after_request(response):256 g.sqlite3_db.close()257 return response258259Learn from Others260-----------------261262This documentation only touches the bare minimum for extension263development. If you want to learn more, it's a very good idea to check264out existing extensions on the `Flask Extension Registry`_. If you feel265lost there is still the `mailinglist`_ and the `IRC channel`_ to get some266ideas for nice looking APIs. Especially if you do something nobody beforeChanged extensiondev docsArmin Ronacherbefore adoption8837678
lines 267–270why, one step back267you did, it might be a very good idea to get some more input. This not268only to get an idea about what people might want to have from an269extension, but also to avoid having multiple developers working on pretty270much the same side by side.Added document about extension developmentArmin Ronacherbefore adoptionee69fb5
line 271why, one step back271Changed extensiondev docsArmin Ronacherbefore adoption8837678
lines 272–277why, one step back272Remember: good API design is hard, so introduce your project on the273mailinglist, and let other developers give you a helping hand with274designing the API.275276The best Flask extensions are extensions that share common idioms for the277API. And this can only work if collaboration happens early.Added document about extension developmentArmin Ronacherbefore adoptionee69fb5
lines 278–279why, one step back278279Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de
lines 280–297why, one step back280Approved Extensions281-------------------282283Flask also has the concept of approved extensions. Approved extensions284are tested as part of Flask itself to ensure extensions do not break on285new releases. These approved extensions are listed on the `Flask286Extension Registry`_ and marked appropriately. If you want your own287extension to be approved you have to follow these guidelines:2882891. An approved Flask extension must provide exactly one package or module290 inside the `flaskext` namespace package.2912. It must ship a testsuite that can either be invoked with ``make test``292 or ``python setup.py test``. For testsuites invoked with ``make293 test`` the extension has to ensure that all dependencies for the test294 are installed automatically, in case of ``python setup.py test``295 dependencies for tests alone can be specified in the `setup.py`296 file. The testsuite also has to be part of the distribution.2973. APIs of approved extensions will be checked for the followingFixed a word in the docsArmin Ronacherbefore adoptionb2fb224
line 298why, one step back298 characteristics:Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de
lines 299–304why, one step back299300 - an approved extension has to support multiple applications301 running in the same Python process.302 - it must be possible to use the factory pattern for creating303 applications.304Approved extensions must not be GPLArmin Ronacherbefore adoptiona7d83a9
line 305why, one step back3054. The license must be BSD/MIT/WTFPL licensed.Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de
lines 306–308why, one step back3065. The naming scheme for official extensions is *Flask-ExtensionName* or307 *ExtensionName-Flask*.3086. Approved extensions must define all their dependencies in theApproved extensions must not be GPLArmin Ronacherbefore adoptiona7d83a9
line 309why, one step back309 `setup.py` file unless a dependency cannot be met because it is notUpdated docs for extension approval processArmin Ronacherbefore adoption3adc9de
line 310why, one step back310 available on PyPI.Fixed wordingArmin Ronacherbefore adoption66c1395
lines 311–312why, one step back3117. The extension must have documentation that uses one of the two Flask312 themes for Sphinx documentation.Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de
lines 313–318why, one step back3138. The setup.py description (and thus the PyPI description) has to314 link to the documentation, website (if there is one) and there315 must be a link to automatically install the development version316 (``PackageName==dev``).317318Added document about extension developmentArmin Ronacherbefore adoptionee69fb5
lines 319–323why, one step back319.. _Flask Extension Wizard:320 http://github.com/mitsuhiko/flask-extension-wizard321.. _OAuth extension: http://packages.python.org/Flask-OAuth/322.. _mailinglist: http://flask.pocoo.org/mailinglist/323.. _IRC channel: http://flask.pocoo.org/community/irc/