Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

334 lines · 12.7 KiB

Last changed by

Merge branch '1.1.x'David Lordbefore adoption40eadfc

History of this file

Take it

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

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 1–4why, one step back
1Flask Extension Development
2===========================34Flask, being a microframework, often requires some repetitive steps to get

Merge branch '1.0.x'David Lordbefore adoption1351d0a

line 5why, one step back
5a third party library working. Many such extensions are already available

Merge branch '1.1.x'David Lordbefore adoptionfb4aab5

line 6why, one step back
6on `PyPI`_.

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 7–156why, one step back
7
8If you want to create your own Flask extension for something that does not9exist yet, this guide to extension development will help you get your10extension running in no time and to feel like users would expect your11extension to behave.1213Anatomy of an Extension14-----------------------1516Extensions are all located in a package called ``flask_something``17where "something" is the name of the library you want to bridge. So for18example if you plan to add support for a library named `simplexml` to19Flask, you would name your extension's package ``flask_simplexml``.2021The name of the actual extension (the human readable name) however would22be something like "Flask-SimpleXML". Make sure to include the name23"Flask" somewhere in that name and that you check the capitalization.24This is how users can then register dependencies to your extension in25their :file:`setup.py` files.2627But what do extensions look like themselves? An extension has to ensure28that it works with multiple Flask application instances at once. This is29a requirement because many people will use patterns like the30:ref:`app-factories` pattern to create their application as needed to aid31unittests and to support multiple configurations. Because of that it is32crucial that your application supports that kind of behavior.3334Most importantly the extension must be shipped with a :file:`setup.py` file and35registered on PyPI. Also the development checkout link should work so36that people can easily install the development version into their37virtualenv without having to download the library by hand.3839Flask extensions must be licensed under a BSD, MIT or more liberal license40in order to be listed in the Flask Extension Registry. Keep in mind41that the Flask Extension Registry is a moderated place and libraries will42be reviewed upfront if they behave as required.4344"Hello Flaskext!"45-----------------4647So let's get started with creating such a Flask extension. The extension48we want to create here will provide very basic support for SQLite3.4950First we create the following folder structure::5152 flask-sqlite3/53 flask_sqlite3.py54 LICENSE55 README5657Here's the contents of the most important files:5859setup.py60````````6162The next file that is absolutely required is the :file:`setup.py` file which is63used to install your Flask extension. The following contents are64something you can work with::6566 """67 Flask-SQLite368 -------------6970 This is the description for that library71 """72 from setuptools import setup737475 setup(76 name='Flask-SQLite3',77 version='1.0',78 url='http://example.com/flask-sqlite3/',79 license='BSD',80 author='Your Name',81 author_email='your-email@example.com',82 description='Very short description',83 long_description=__doc__,84 py_modules=['flask_sqlite3'],85 # if you would be using a package instead use packages instead86 # of py_modules:87 # packages=['flask_sqlite3'],88 zip_safe=False,89 include_package_data=True,90 platforms='any',91 install_requires=[92 'Flask'93 ],94 classifiers=[95 'Environment :: Web Environment',96 'Intended Audience :: Developers',97 'License :: OSI Approved :: BSD License',98 'Operating System :: OS Independent',99 'Programming Language :: Python',100 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',101 'Topic :: Software Development :: Libraries :: Python Modules'102 ]103 )104105That's a lot of code but you can really just copy/paste that from existing106extensions and adapt.107108flask_sqlite3.py109````````````````110111Now this is where your extension code goes. But how exactly should such112an extension look like? What are the best practices? Continue reading113for some insight.114115Initializing Extensions116-----------------------117118Many extensions will need some kind of initialization step. For example,119consider an application that's currently connecting to SQLite like the120documentation suggests (:ref:`sqlite3`). So how does the extension121know the name of the application object?122123Quite simple: you pass it to it.124125There are two recommended ways for an extension to initialize:126127initialization functions:128129 If your extension is called `helloworld` you might have a function130 called ``init_helloworld(app[, extra_args])`` that initializes the131 extension for that application. It could attach before / after132 handlers etc.133134classes:135136 Classes work mostly like initialization functions but can later be137 used to further change the behavior. For an example look at how the138 `OAuth extension`_ works: there is an `OAuth` object that provides139 some helper functions like `OAuth.remote_app` to create a reference to140 a remote application that uses OAuth.141142What to use depends on what you have in mind. For the SQLite 3 extension143we will use the class-based approach because it will provide users with an144object that handles opening and closing database connections.145146When designing your classes, it's important to make them easily reusable147at the module level. This means the object itself must not under any148circumstances store any application specific state and must be shareable149between different applications.150151The Extension Code152------------------153154Here's the contents of the `flask_sqlite3.py` for copy/paste::155156 import sqlite3

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

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

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 158–167why, one step back
158
159160 class SQLite3(object):161 def __init__(self, app=None):162 self.app = app163 if app is not None:164 self.init_app(app)165166 def init_app(self, app):167 app.config.setdefault('SQLITE3_DATABASE', ':memory:')

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

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

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 169–173why, one step back
169
170 def connect(self):171 return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])172173 def teardown(self, exception):

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

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

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 175–179why, one step back
175 if hasattr(ctx, 'sqlite3_db'):
176 ctx.sqlite3_db.close()177178 @property179 def connection(self):

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

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

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 181–194why, one step back
181 if ctx is not None:
182 if not hasattr(ctx, 'sqlite3_db'):183 ctx.sqlite3_db = self.connect()184 return ctx.sqlite3_db185186187So here's what these lines of code do:1881891. The ``__init__`` method takes an optional app object and, if supplied, will190 call ``init_app``.1912. The ``init_app`` method exists so that the ``SQLite3`` object can be192 instantiated without requiring an app object. This method supports the193 factory pattern for creating applications. The ``init_app`` will set the194 configuration for the database, defaulting to an in memory database if

Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a

lines 195–196why, one step back
195 no configuration is supplied. In addition, the ``init_app`` method
196 attaches the ``teardown`` handler.

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 197–205why, one step back
1973. Next, we define a ``connect`` method that opens a database connection.
1984. Finally, we add a ``connection`` property that on first access opens199 the database connection and stores it on the context. This is also200 the recommended way to handling resources: fetch resources lazily the201 first time they are used.202203 Note here that we're attaching our database connection to the top204 application context via ``_app_ctx_stack.top``. Extensions should use205 the top context for storing their own information with a sufficiently

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

line 206why, one step back
206 complex name.

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 207–224why, one step back
207
208So why did we decide on a class-based approach here? Because using our209extension looks something like this::210211 from flask import Flask212 from flask_sqlite3 import SQLite3213214 app = Flask(__name__)215 app.config.from_pyfile('the-config.cfg')216 db = SQLite3(app)217218You can then use the database from views like this::219220 @app.route('/')221 def show_all():222 cur = db.connection.cursor()223 cur.execute(...)224

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

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

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 227–237why, one step back
227
228 with app.app_context():229 cur = db.connection.cursor()230 cur.execute(...)231232At the end of the ``with`` block the teardown handles will be executed233automatically.234235Additionally, the ``init_app`` method is used to support the factory pattern236for creating apps::237

Merge pull request #3071 from bbbbx/masterHsiaoming Yangbefore adoption33c89aa

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

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 239–273why, one step back
239 # Then later on.
240 app = create_app('the-config.cfg')241 db.init_app(app)242243Keep in mind that supporting this factory pattern for creating apps is required244for approved flask extensions (described below).245246.. admonition:: Note on ``init_app``247248 As you noticed, ``init_app`` does not assign ``app`` to ``self``. This249 is intentional! Class based Flask extensions must only store the250 application on the object when the application was passed to the251 constructor. This tells the extension: I am not interested in using252 multiple applications.253254 When the extension needs to find the current application and it does255 not have a reference to it, it must either use the256 :data:`~flask.current_app` context local or change the API in a way257 that you can pass the application explicitly.258259260Using _app_ctx_stack261--------------------262263In the example above, before every request, a ``sqlite3_db`` variable is264assigned to ``_app_ctx_stack.top``. In a view function, this variable is265accessible using the ``connection`` property of ``SQLite3``. During the266teardown of a request, the ``sqlite3_db`` connection is closed. By using267this pattern, the *same* connection to the sqlite3 database is accessible268to anything that needs it for the duration of the request.269270271Learn from Others272-----------------273

Merge branch '1.1.x'David Lordbefore adoptionfb4aab5

lines 274–276why, one step back
274This documentation only touches the bare minimum for extension development.
275If you want to learn more, it's a very good idea to check out existing extensions276on the `PyPI`_. If you feel lost there is still the `mailinglist`_ and the

Merge branch '1.1.x'David Lordbefore adoption40eadfc

line 277why, one step back
277`Discord server`_ to get some ideas for nice looking APIs. Especially if you do

Merge branch '1.1.x'David Lordbefore adoptionfb4aab5

lines 278–281why, one step back
278something nobody before you did, it might be a very good idea to get some more
279input. This not only generates useful feedback on what people might want from280an extension, but also avoids having multiple developers working in isolation281on pretty much the same problem.

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 282–283why, one step back
282
283Remember: good API design is hard, so introduce your project on the

Merge branch '1.0.x'David Lordbefore adoption2236ba9

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

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 285–292why, one step back
285designing the API.
286287The best Flask extensions are extensions that share common idioms for the288API. And this can only work if collaboration happens early.289290Approved Extensions291-------------------292

Merge branch '1.1.x'David Lordbefore adoption40eadfc

lines 293–297why, one step back
293Flask previously had the concept of approved extensions. These came with
294some vetting of support and compatibility. While this list became too295difficult to maintain over time, the guidelines are still relevant to296all extensions maintained and developed today, as they help the Flask297ecosystem remain consistent and compatible.

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 298–299why, one step back
298
2990. An approved Flask extension requires a maintainer. In the event an

Merge branch '1.1.x'David Lordbefore adoption40eadfc

lines 300–309why, one step back
300 extension author would like to move beyond the project, the project
301 should find a new maintainer and transfer access to the repository,302 documentation, PyPI, and any other services. If no maintainer303 is available, give access to the Pallets core team.3041. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*.305 It must provide exactly one package or module named306 ``flask_extension_name``.3072. The extension must be BSD or MIT licensed. It must be open source308 and publicly available.3093. The extension's API must have the following characteristics:

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

line 310why, one step back
310

Merge branch '1.1.x'David Lordbefore adoption40eadfc

lines 311–315why, one step back
311 - It must support multiple applications running in the same Python
312 process. Use ``current_app`` instead of ``self.app``, store313 configuration and state per application instance.314 - It must be possible to use the factory pattern for creating315 applications. Use the ``ext.init_app()`` pattern.

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

line 316why, one step back
316

Merge branch '1.1.x'David Lordbefore adoption40eadfc

lines 317–327why, one step back
3174. From a clone of the repository, an extension with its dependencies
318 must be installable with ``pip install -e .``.3195. It must ship a testing suite that can be invoked with ``tox -e py``320 or ``pytest``. If not using ``tox``, the test dependencies should be321 specified in a ``requirements.txt`` file. The tests must be part of322 the sdist distribution.3236. The documentation must use the ``flask`` theme from the324 `Official Pallets Themes`_. A link to the documentation or project325 website must be in the PyPI metadata or the readme.3267. The active versions of Python should be supported. As of 2020 this327 means Python 3.5 and newer.

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

lines 328–329why, one step back
328
329

Merge branch '1.1.x'David Lordbefore adoptionfb4aab5

line 330why, one step back
330.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask

Merge pull request #2593 from pallets/env-docsDavid Lordbefore adoptionc3a9978

line 331why, one step back
331.. _OAuth extension: https://pythonhosted.org/Flask-OAuth/

Merge branch '1.1.x'David Lordbefore adoption40eadfc

lines 332–333why, one step back
332.. _mailinglist: https://mail.python.org/mailman/listinfo/flask
333.. _Discord server: https://discord.gg/t6rrQZH

Merge branch '1.0.x'David Lordbefore adoption1351d0a

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