Added document about extension development
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 707b307 · Browse files · 3 files·+277 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+277 added−0 removed
- other:+277 added−0 removed
Provenance
- Commit
ee69fb5- Tree
a2296dc- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
707b307
3 files changed+277 added−0 removed
modified:docs/_themesnot shown
Its text is not shown, modified.
modified:docs/contents.rst.inc+1 added
38 unmodified lines39 .. toctree::40 :maxdepth: 241 42 design43+ extensiondev44 license45 upgrading46 changelogadded:docs/extensiondev.rst+276 added
1+Flask Extension Development2+===========================3+4+Flask, being a microframework, often requires some repetitive steps to get5+a third party library working. Because very often these steps could be6+abstracted to support multiple projects the `Flask Extension Registry`_7+was created.8+9+If you want to create your own Flask extension for something that does not10+exist yet, this guide to extension development will help you get your11+extension running in no time and to feel like users would expect your12+extension to behave.13+14+.. _Flask Extension Registry: http://flask.pocoo.org/extensions/15+16+Anatomy of an Extension17+-----------------------18+19+Extensions are all located in a package called ``flaskext.something``20+where "something" is the name of the library you want to bridge. So for21+example if you plan to add support for a library named `simplexml` to22+Flask, you would name your extension's package ``flaskext.simplexml``.23+24+The name of the actual extension (the human readable name) however would25+be something like "Flask-SimpleXML". Make sure to include the name26+"Flask" somewhere in that name and that you check the capitalization.27+This is how users can then register dependencies to your extension in28+their `setup.py` files.29+30+The magic that makes it possible to have your library in a package called31+``flaskext.something`` is called a "namespace package". Check out the32+guide below how to create something like that.33+34+But how do extensions look like themselves? An extension has to ensure35+that it works with multiple Flask application instances at once. This is36+a requirement because many people will use patterns like the37+:ref:`app-factories` pattern to create their application as needed to aid38+unittests and to support multiple configurations. Because of that it is39+crucial that your application supports that kind of behaviour.40+41+Most importantly the extension must be shipped with a `setup.py` file and42+registered on PyPI. Also the development checkout link should work so43+that people can easily install the development version into their44+virtualenv without having to download the library by hand.45+46+Flask extensions must be licensed as BSD or MIT or a more liberal license47+to be enlisted on the Flask Extension Registry. Keep in mind that the48+Flask Extension Registry is a moderated place and libraries will be49+reviewed upfront if they behave as required.50+51+"Hello Flaskext!"52+-----------------53+54+So let's get started with creating such a Flask extension. The extension55+we want to create here will provide very basic support for SQLite3.56+57+There is a script on github called `Flask Extension Wizard`_ which helps58+you create the initial folder structure. But for this very basic example59+we want to create all by hand to get a better feeling for it.60+61+First we create the following folder structure::62+63+ flask-sqlite3/64+ flaskext/65+ __init__.py66+ sqlite3.py67+ setup.py68+ LICENSE69+70+Here the contents of the most important files:71+72+flaskext/__init__.py73+````````````````````74+75+The only purpose of this file is to mark the package as namespace package.76+This is required so that multiple modules from different PyPI packages can77+reside in the same Python package::78+79+ __import__('pkg_resources').declare_namespace(__name__)80+81+If you want to know exactly what is happening there, checkout the82+distribute or setuptools docs which explain how this works.83+84+Just make sure to not put anything else in there!85+86+setup.py87+````````88+89+The next file that is absolutely required is the `setup.py` file which is90+used to install your Flask extension. The following contents are91+something you can work with::92+93+ """94+ Flask-SQLite395+ -------------96+97+ This is the description for that library98+ """99+ from setuptools import setup100+101+102+ 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+ )128+129+That's a lot of code but you can really just copy/paste that from existing130+extensions and adapt. This is also what the wizard creates for you if you131+use it.132+133+flaskext/sqlite3.py134+```````````````````135+136+Now this is where your extension code goes. But how exactly should such137+an extension look like? What are the best practices? Continue reading138+for some insight.139+140+141+Initializing Extensions142+-----------------------143+144+Many extensions will need some kind of initialization step. For example,145+consider your application is currently connecting to SQLite like the146+documentation suggests (:ref:`sqlite3`) you will need to provide a few147+functions and before / after request handlers. So how does the extension148+know the name of the application object?149+150+Quite simple: you pass it to it.151+152+There are two recommended ways for an extension to initialize:153+154+initialization 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.159+160+classes:161+ Classes work mostly like initialization functions but can later be162+ used to further change the behaviour. For an example look at how the163+ `OAuth extension`_ works: ther is an `OAuth` object that provides164+ some helper functions like `OAuth.remote_app` to create a reference to165+ a remote application that uses OAuth.166+167+What to use depends on what you have in mind. For the SQLite 3 extension168+we will need to use the class based approach because we have to use a169+controller object that can be used to connect to the database.170+171+The Extension Code172+------------------173+174+Here the contents of the `flaskext/sqlite3.py` for copy/paste::175+176+ from __future__ import absolute_import177+ import sqlite3178+ from flask import g179+180+ class SQLite3(object):181+ 182+ def __init__(self, app):183+ self.app = app184+ self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')185+186+ self.app.before_request(self.before_request)187+ self.app.after_request(self.after_request)188+189+ def connect(self):190+ return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])191+192+ def before_request(self):193+ g.sqlite3_db = self.connect()194+195+ def after_request(self, response):196+ g.sqlite3_db.close()197+ return response198+199+So here what the lines of code do:200+201+1. 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.205+2. 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.208+3. Then it implements a `connect` function that returns a new database209+ connection and the two handlers.210+211+So why did we decide on a class based approach here? Because using that212+extension looks something like this::213+214+ from flask import Flask, g215+ from flaskext.sqlite3 import SQLite3216+217+ app = Flask(__name__)218+ app.config.from_pyfile('the-config.cfg')219+ db = SQLite(app)220+221+Either way you can use the database from the views like this::222+223+ @app.route('/')224+ def show_all():225+ cur = g.sqlite_db.cursor()226+ cur.execute(...)227+228+But how would you open a database connection from outside a view function?229+This is where the `db` object now comes into play:230+231+>>> from yourapplication import db232+>>> con = db.connect()233+>>> cur = con.cursor()234+235+If you don't need that, you can go with initialization functions.236+237+Initialization Functions238+------------------------239+240+Here how the module would look like with initialization functions::241+242+ from __future__ import absolute_import243+ import sqlite3244+ from flask import g245+246+ def init_sqlite3(app):247+ app = app248+ app.config.setdefault('SQLITE3_DATABASE', ':memory:')249+250+ @app.before_request251+ def before_request():252+ g.sqlite3_db = sqlite3.connect(self.app.config['SQLITE3_DATABASE'])253+254+ @app.after_request255+ def after_request(response):256+ g.sqlite3_db.close()257+ return response258+259+Learn from Others260+-----------------261+262+This documentation only touches the bare minimum for extension263+development. If you want to learn more, it's a very good idea to check264+out existing extensions on the `Flask Extension Registry`_. If you feel265+lost there is still the `mailinglist`_ and the `IRC channel`_ to get some266+ideas for nice looking APIs. Especially if you do something nobody before267+you did, it might be a very good idea to get some more input.268+269+Remember: good API design is hard :(270+271+272+.. _Flask Extension Wizard:273+ http://github.com/mitsuhiko/flask-extension-wizard274+.. _OAuth extension: http://packages.python.org/Flask-OAuth/275+.. _mailinglist: http://flask.pocoo.org/mailinglist/276+.. _IRC channel: http://flask.pocoo.org/community/irc/