Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

344 lines · 13.1 KiB

Last changed by

Merge pull request #3270 from pallets/metadataDavid Lordbefore adoption31d3c7e

History of this file

Take it

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

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 1–6why, one step back
1.. _extension-dev:
23Flask Extension Development4===========================56Flask, being a microframework, often requires some repetitive steps to get

Merge pull request #3270 from pallets/metadataDavid Lordbefore adoption31d3c7e

lines 7–8why, one step back
7a third party library working. Many such extensions are already available
8on `PyPI <https://pypi.org/search/?c=Framework+%3A%3A+Flask>`_.

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 9–160why, one step back
9
10If you want to create your own Flask extension for something that does not11exist yet, this guide to extension development will help you get your12extension running in no time and to feel like users would expect your13extension to behave.1415.. _Flask Extension Registry: http://flask.pocoo.org/extensions/1617Anatomy of an Extension18-----------------------1920Extensions are all located in a package called ``flask_something``21where "something" is the name of the library you want to bridge. So for22example if you plan to add support for a library named `simplexml` to23Flask, you would name your extension's package ``flask_simplexml``.2425The name of the actual extension (the human readable name) however would26be something like "Flask-SimpleXML". Make sure to include the name27"Flask" somewhere in that name and that you check the capitalization.28This is how users can then register dependencies to your extension in29their :file:`setup.py` files.3031But what do extensions look like themselves? An extension has to ensure32that it works with multiple Flask application instances at once. This is33a requirement because many people will use patterns like the34:ref:`app-factories` pattern to create their application as needed to aid35unittests and to support multiple configurations. Because of that it is36crucial that your application supports that kind of behavior.3738Most importantly the extension must be shipped with a :file:`setup.py` file and39registered on PyPI. Also the development checkout link should work so40that people can easily install the development version into their41virtualenv without having to download the library by hand.4243Flask extensions must be licensed under a BSD, MIT or more liberal license44in order to be listed in the Flask Extension Registry. Keep in mind45that the Flask Extension Registry is a moderated place and libraries will46be reviewed upfront if they behave as required.4748"Hello Flaskext!"49-----------------5051So let's get started with creating such a Flask extension. The extension52we want to create here will provide very basic support for SQLite3.5354First we create the following folder structure::5556 flask-sqlite3/57 flask_sqlite3.py58 LICENSE59 README6061Here's the contents of the most important files:6263setup.py64````````6566The next file that is absolutely required is the :file:`setup.py` file which is67used to install your Flask extension. The following contents are68something you can work with::6970 """71 Flask-SQLite372 -------------7374 This is the description for that library75 """76 from setuptools import setup777879 setup(80 name='Flask-SQLite3',81 version='1.0',82 url='http://example.com/flask-sqlite3/',83 license='BSD',84 author='Your Name',85 author_email='your-email@example.com',86 description='Very short description',87 long_description=__doc__,88 py_modules=['flask_sqlite3'],89 # if you would be using a package instead use packages instead90 # of py_modules:91 # packages=['flask_sqlite3'],92 zip_safe=False,93 include_package_data=True,94 platforms='any',95 install_requires=[96 'Flask'97 ],98 classifiers=[99 'Environment :: Web Environment',100 'Intended Audience :: Developers',101 'License :: OSI Approved :: BSD License',102 'Operating System :: OS Independent',103 'Programming Language :: Python',104 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',105 'Topic :: Software Development :: Libraries :: Python Modules'106 ]107 )108109That's a lot of code but you can really just copy/paste that from existing110extensions and adapt.111112flask_sqlite3.py113````````````````114115Now this is where your extension code goes. But how exactly should such116an extension look like? What are the best practices? Continue reading117for some insight.118119Initializing Extensions120-----------------------121122Many extensions will need some kind of initialization step. For example,123consider an application that's currently connecting to SQLite like the124documentation suggests (:ref:`sqlite3`). So how does the extension125know the name of the application object?126127Quite simple: you pass it to it.128129There are two recommended ways for an extension to initialize:130131initialization functions:132133 If your extension is called `helloworld` you might have a function134 called ``init_helloworld(app[, extra_args])`` that initializes the135 extension for that application. It could attach before / after136 handlers etc.137138classes:139140 Classes work mostly like initialization functions but can later be141 used to further change the behavior. For an example look at how the142 `OAuth extension`_ works: there is an `OAuth` object that provides143 some helper functions like `OAuth.remote_app` to create a reference to144 a remote application that uses OAuth.145146What to use depends on what you have in mind. For the SQLite 3 extension147we will use the class-based approach because it will provide users with an148object that handles opening and closing database connections.149150When designing your classes, it's important to make them easily reusable151at the module level. This means the object itself must not under any152circumstances store any application specific state and must be shareable153between different applications.154155The Extension Code156------------------157158Here's the contents of the `flask_sqlite3.py` for copy/paste::159160 import sqlite3

Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d

line 161why, one step back
161 from flask import current_app, _app_ctx_stack

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 162–171why, one step back
162
163164 class SQLite3(object):165 def __init__(self, app=None):166 self.app = app167 if app is not None:168 self.init_app(app)169170 def init_app(self, app):171 app.config.setdefault('SQLITE3_DATABASE', ':memory:')

Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d

line 172why, one step back
172 app.teardown_appcontext(self.teardown)

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 173–177why, one step back
173
174 def connect(self):175 return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])176177 def teardown(self, exception):

Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d

line 178why, one step back
178 ctx = _app_ctx_stack.top

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 179–183why, one step back
179 if hasattr(ctx, 'sqlite3_db'):
180 ctx.sqlite3_db.close()181182 @property183 def connection(self):

Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d

line 184why, one step back
184 ctx = _app_ctx_stack.top

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 185–199why, one step back
185 if ctx is not None:
186 if not hasattr(ctx, 'sqlite3_db'):187 ctx.sqlite3_db = self.connect()188 return ctx.sqlite3_db189190191So here's what these lines of code do:1921931. The ``__init__`` method takes an optional app object and, if supplied, will194 call ``init_app``.1952. The ``init_app`` method exists so that the ``SQLite3`` object can be196 instantiated without requiring an app object. This method supports the197 factory pattern for creating applications. The ``init_app`` will set the198 configuration for the database, defaulting to an in memory database if199 no configuration is supplied. In addition, the ``init_app`` method attaches

Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d

line 200why, one step back
200 the ``teardown`` handler.

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 201–209why, one step back
2013. Next, we define a ``connect`` method that opens a database connection.
2024. Finally, we add a ``connection`` property that on first access opens203 the database connection and stores it on the context. This is also204 the recommended way to handling resources: fetch resources lazily the205 first time they are used.206207 Note here that we're attaching our database connection to the top208 application context via ``_app_ctx_stack.top``. Extensions should use209 the top context for storing their own information with a sufficiently

Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d

line 210why, one step back
210 complex name.

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 211–228why, one step back
211
212So why did we decide on a class-based approach here? Because using our213extension looks something like this::214215 from flask import Flask216 from flask_sqlite3 import SQLite3217218 app = Flask(__name__)219 app.config.from_pyfile('the-config.cfg')220 db = SQLite3(app)221222You can then use the database from views like this::223224 @app.route('/')225 def show_all():226 cur = db.connection.cursor()227 cur.execute(...)228

Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d

lines 229–230why, one step back
229Likewise if you are outside of a request you can use the database by
230pushing an app context::

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 231–241why, one step back
231
232 with app.app_context():233 cur = db.connection.cursor()234 cur.execute(...)235236At the end of the ``with`` block the teardown handles will be executed237automatically.238239Additionally, the ``init_app`` method is used to support the factory pattern240for creating apps::241

fix the typovenusbefore adoption8c97969

line 242why, one step back
242 db = SQLite3()

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 243–288why, one step back
243 # Then later on.
244 app = create_app('the-config.cfg')245 db.init_app(app)246247Keep in mind that supporting this factory pattern for creating apps is required248for approved flask extensions (described below).249250.. admonition:: Note on ``init_app``251252 As you noticed, ``init_app`` does not assign ``app`` to ``self``. This253 is intentional! Class based Flask extensions must only store the254 application on the object when the application was passed to the255 constructor. This tells the extension: I am not interested in using256 multiple applications.257258 When the extension needs to find the current application and it does259 not have a reference to it, it must either use the260 :data:`~flask.current_app` context local or change the API in a way261 that you can pass the application explicitly.262263264Using _app_ctx_stack265--------------------266267In the example above, before every request, a ``sqlite3_db`` variable is268assigned to ``_app_ctx_stack.top``. In a view function, this variable is269accessible using the ``connection`` property of ``SQLite3``. During the270teardown of a request, the ``sqlite3_db`` connection is closed. By using271this pattern, the *same* connection to the sqlite3 database is accessible272to anything that needs it for the duration of the request.273274275Learn from Others276-----------------277278This documentation only touches the bare minimum for extension279development. If you want to learn more, it's a very good idea to check280out existing extensions on the `Flask Extension Registry`_. If you feel281lost there is still the `mailinglist`_ and the `IRC channel`_ to get some282ideas for nice looking APIs. Especially if you do something nobody before283you did, it might be a very good idea to get some more input. This not only284generates useful feedback on what people might want from an extension, but285also avoids having multiple developers working in isolation on pretty much the286same problem.287288Remember: good API design is hard, so introduce your project on the

Merge pull request #3199 from alecbrooks/masterDavid Lordbefore adoptionded0f68

line 289why, one step back
289mailing list, and let other developers give you a helping hand with

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 290–329why, one step back
290designing the API.
291292The best Flask extensions are extensions that share common idioms for the293API. And this can only work if collaboration happens early.294295Approved Extensions296-------------------297298Flask also has the concept of approved extensions. Approved extensions299are tested as part of Flask itself to ensure extensions do not break on300new releases. These approved extensions are listed on the `Flask301Extension Registry`_ and marked appropriately. If you want your own302extension to be approved you have to follow these guidelines:3033040. An approved Flask extension requires a maintainer. In the event an305 extension author would like to move beyond the project, the project should306 find a new maintainer including full source hosting transition and PyPI307 access. If no maintainer is available, give access to the Flask core team.3081. An approved Flask extension must provide exactly one package or module309 named ``flask_extensionname``.3102. It must ship a testing suite that can either be invoked with ``make test``311 or ``python setup.py test``. For test suites invoked with ``make312 test`` the extension has to ensure that all dependencies for the test313 are installed automatically. If tests are invoked with ``python setup.py314 test``, test dependencies can be specified in the :file:`setup.py` file. The315 test suite also has to be part of the distribution.3163. APIs of approved extensions will be checked for the following317 characteristics:318319 - an approved extension has to support multiple applications320 running in the same Python process.321 - it must be possible to use the factory pattern for creating322 applications.3233244. The license must be BSD/MIT/WTFPL licensed.3255. The naming scheme for official extensions is *Flask-ExtensionName* or326 *ExtensionName-Flask*.3276. Approved extensions must define all their dependencies in the328 :file:`setup.py` file unless a dependency cannot be met because it is not329 available on PyPI.

Merge pull request #3270 from pallets/metadataDavid Lordbefore adoption31d3c7e

lines 330–331why, one step back
3307. The documentation must use the ``flask`` theme from the
331 `Official Pallets Themes`_.

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 332–337why, one step back
3328. The setup.py description (and thus the PyPI description) has to
333 link to the documentation, website (if there is one) and there334 must be a link to automatically install the development version335 (``PackageName==dev``).3369. The ``zip_safe`` flag in the setup script must be set to ``False``,337 even if the extension would be safe for zipping.

Merge pull request #2555 from pallets/deprecate-26-33David Lordbefore adoption05e3840

line 338why, one step back
33810. An extension currently has to support Python 3.4 and newer and 2.7.

Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa

lines 339–343why, one step back
339
340341.. _OAuth extension: https://pythonhosted.org/Flask-OAuth/342.. _mailinglist: http://flask.pocoo.org/mailinglist/343.. _IRC channel: http://flask.pocoo.org/community/irc/

Merge pull request #3270 from pallets/metadataDavid Lordbefore adoption31d3c7e

line 344why, one step back
344.. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/