Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

362 lines · 13.3 KiB

Last changed by

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

History of this file

Take it

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

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 1–69why, 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-----------------------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 LICENSE69

Fix some typos in the docsjgraemebefore adoptionff2786d

line 70why, one step back
70Here's the contents of the most important files:

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 71–154why, one step back
71
72flaskext/__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 function

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

line 155why, one step back
155 called ``init_helloworld(app[, extra_args])`` that initializes the

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 156–166why, one step back
156 extension for that application. It could attach before / after
157 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 extension

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 167–168why, one step back
167we will use the class based approach because it will provide users with a
168manager object that handles opening and closing database connections.

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 169–172why, one step back
169
170The Extension Code171------------------172

Fix some typos in the docsjgraemebefore adoptionff2786d

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

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 174–177why, one step back
174
175 from __future__ import absolute_import176 import sqlite3177

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 178–179why, one step back
178 from flask import _request_ctx_stack
179

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 180why, one step back
180 class SQLite3(object):

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

line 181why, one step back
181

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 182–185why, one step back
182 def __init__(self, app):
183 self.app = app184 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')185 self.app.after_request(self.after_request)

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

line 186why, one step back
186 self.app.before_request(self.before_request)

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 187–191why, one step back
187
188 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 back
192 ctx = _request_ctx_stack.top
193 ctx.sqlite3_db = self.connect()

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

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

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 196–197why, one step back
196 ctx = _request_ctx_stack.top
197 ctx.sqlite3_db.close()

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 198–199why, one step back
198 return response
199

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 200–203why, one step back
200 def get_db(self):
201 ctx = _request_ctx_stack.top202 if ctx is not None:203 return ctx.sqlite3_db

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 204why, one step back
204

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

line 205why, one step back
205So here's what these lines of code do:

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 206why, one step back
206

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 207–223why, one step back
2071. The ``__future__`` import is necessary to activate absolute imports.
208 Otherwise we could not call our module `sqlite3.py` and import the209 top-level `sqlite3` module which actually implements the connection to210 SQLite.2112. We create a class for our extension that requires a supplied `app` object,212 sets a configuration for the database if it's not there213 (:meth:`dict.setdefault`), and attaches `before_request` and214 `after_request` handlers.2153. Next, we define a `connect` function that opens a database connection.2164. Then we set up the request handlers we bound to the app above. Note here217 that we're attaching our database connection to the top request context via218 `_request_ctx_stack.top`. Extensions should use the top context and not the219 `g` object to store things like database connections.2205. Finally, we add a `get_db` function that simplifies access to the context's221 database.222223So why did we decide on a class based approach here? Because using our

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 224–225why, one step back
224extension looks something like this::
225

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

line 226why, one step back
226 from flask import Flask

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 227–230why, one step back
227 from flaskext.sqlite3 import SQLite3
228229 app = Flask(__name__)230 app.config.from_pyfile('the-config.cfg')

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 231–232why, one step back
231 manager = SQLite3(app)
232 db = manager.get_db()

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 233why, one step back
233

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

line 234why, one step back
234You can then use the database from views like this::

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 235–237why, one step back
235
236 @app.route('/')237 def show_all():

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

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

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 239–240why, one step back
239 cur.execute(...)
240

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

line 241why, one step back
241Opening a database connection from outside a view function is simple.

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 242–243why, one step back
242
243>>> from yourapplication import db

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 244–245why, one step back
244>>> cur = db.cursor()
245>>> cur.execute(...)

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 246why, one step back
246

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 247–248why, one step back
247Adding an `init_app` Function
248-----------------------------

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 249why, one step back
249

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 250–253why, one step back
250In practice, you'll almost always want to permit users to initialize your
251extension and provide an app object after the fact. This can help avoid252circular import problems when a user is breaking their app into multiple files.253Our extension could add an `init_app` function as follows::

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 254why, one step back
254

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

line 255why, one step back
255 class SQLite3(object):

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 256why, one step back
256

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 257–262why, one step back
257 def __init__(self, app=None):
258 if app is not None:259 self.app = app260 self.init_app(self.app)261 else:262 self.app = None

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 263why, one step back
263

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 264–268why, one step back
264 def init_app(self, app):
265 self.app = app266 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')267 self.app.after_request(self.after_request)268 self.app.before_request(self.before_request)

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 269why, one step back
269

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 270–271why, one step back
270 def connect(self):
271 return sqlite3.connect(app.config['SQLITE3_DATABASE'])

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 272why, one step back
272

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 273–279why, one step back
273 def before_request(self):
274 ctx = _request_ctx_stack.top275 ctx.sqlite3_db = self.connect()276277 def after_request(self, response):278 ctx = _request_ctx_stack.top279 ctx.sqlite3_db.close()

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 280–281why, one step back
280 return response
281

Merge remote branch 'mattd/extensions-docs'Armin Ronacherbefore adoptionfd0862c

lines 282–294why, one step back
282 def get_db(self):
283 ctx = _request_ctx_stack.top284 if ctx is not None:285 return ctx.sqlite3_db286287The user could then initialize the extension in one file::288289 manager = SQLite3()290291and bind their app to the extension in another file::292293 manager.init_app(app)294

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 295–302why, one step back
295Learn from Others
296-----------------297298This documentation only touches the bare minimum for extension299development. If you want to learn more, it's a very good idea to check300out existing extensions on the `Flask Extension Registry`_. If you feel301lost there is still the `mailinglist`_ and the `IRC channel`_ to get some302ideas for nice looking APIs. Especially if you do something nobody before

Changed extensiondev docsArmin Ronacherbefore adoption8837678

lines 303–306why, one step back
303you did, it might be a very good idea to get some more input. This not
304only to get an idea about what people might want to have from an305extension, but also to avoid having multiple developers working on pretty306much the same side by side.

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 307why, one step back
307

Changed extensiondev docsArmin Ronacherbefore adoption8837678

lines 308–313why, one step back
308Remember: good API design is hard, so introduce your project on the
309mailinglist, and let other developers give you a helping hand with310designing the API.311312The best Flask extensions are extensions that share common idioms for the313API. And this can only work if collaboration happens early.

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

line 314why, one step back
314

Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de

lines 315–325why, one step back
315Approved Extensions
316-------------------317318Flask also has the concept of approved extensions. Approved extensions319are tested as part of Flask itself to ensure extensions do not break on320new releases. These approved extensions are listed on the `Flask321Extension Registry`_ and marked appropriately. If you want your own322extension to be approved you have to follow these guidelines:3233241. An approved Flask extension must provide exactly one package or module325 inside the `flaskext` namespace package.

Fixed some small typos in the documentation.Sam Andersonbefore adoptionda00160

lines 326–327why, one step back
3262. It must ship a testing suite that can either be invoked with ``make test``
327 or ``python setup.py test``. For test suites invoked with ``make

Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de

lines 328–330why, one step back
328 test`` the extension has to ensure that all dependencies for the test
329 are installed automatically, in case of ``python setup.py test``330 dependencies for tests alone can be specified in the `setup.py`

Fixed some small typos in the documentation.Sam Andersonbefore adoptionda00160

line 331why, one step back
331 file. The test suite also has to be part of the distribution.

Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de

line 332why, one step back
3323. APIs of approved extensions will be checked for the following

Fixed a word in the docsArmin Ronacherbefore adoptionb2fb224

line 333why, one step back
333 characteristics:

Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de

lines 334–339why, one step back
334
335 - an approved extension has to support multiple applications336 running in the same Python process.337 - it must be possible to use the factory pattern for creating338 applications.339

Approved extensions must not be GPLArmin Ronacherbefore adoptiona7d83a9

line 340why, one step back
3404. The license must be BSD/MIT/WTFPL licensed.

Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de

lines 341–343why, one step back
3415. The naming scheme for official extensions is *Flask-ExtensionName* or
342 *ExtensionName-Flask*.3436. Approved extensions must define all their dependencies in the

Approved extensions must not be GPLArmin Ronacherbefore adoptiona7d83a9

line 344why, one step back
344 `setup.py` file unless a dependency cannot be met because it is not

Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de

line 345why, one step back
345 available on PyPI.

Fixed wordingArmin Ronacherbefore adoption66c1395

lines 346–347why, one step back
3467. The extension must have documentation that uses one of the two Flask
347 themes for Sphinx documentation.

Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de

lines 348–351why, one step back
3488. The setup.py description (and thus the PyPI description) has to
349 link to the documentation, website (if there is one) and there350 must be a link to automatically install the development version351 (``PackageName==dev``).

Fixed typoArmin Ronacherbefore adoption3da165f

line 352why, one step back
3529. The ``zip_safe`` flag in the setup script must be set to ``False``,

Mentioned zip_safeArmin Ronacherbefore adoption312dfb4

line 353why, one step back
353 even if the extension would be safe for zipping.

Added another rule to the approval list. 2.5-2.7 compatibilityArmin Ronacherbefore adoption27ce5cc

lines 354–355why, one step back
35410. An extension currently has to support Python 2.5, 2.6 as well as
355 Python 2.7

Updated docs for extension approval processArmin Ronacherbefore adoption3adc9de

lines 356–357why, one step back
356
357

Documented change regarding the session cookie domain policy in the CHANGESArmin Ronacherbefore adoption60e143e

lines 358–362why, one step back
358.. _Flask Extension Wizard:
359 http://github.com/mitsuhiko/flask-extension-wizard360.. _OAuth extension: http://packages.python.org/Flask-OAuth/361.. _mailinglist: http://flask.pocoo.org/mailinglist/362.. _IRC channel: http://flask.pocoo.org/community/irc/