extensiondev.rst
This file
Path
docs/extensiondev.rst
332 lines · 12.6 KiB
Last changed by
Merge pull request #4335 from pallets/drop-python-3.6David Lordbefore adoptionea93a52
History of this fileTake it
The walk stopped after 200 commits: lines older than 6eeb912 point at it.
Merge remote-tracking branch 'origin/1.1.x'David Lordbefore adoption6eeb912
lines 1–137why, one step back1Flask Extension Development2===========================34Flask, being a microframework, often requires some repetitive steps to get5a third party library working. Many such extensions are already available6on `PyPI`_.78If 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:doc:`/patterns/appfactories` pattern to create their application as31needed to aid unittests and to support multiple configurations. Because32of that it is crucial that your application supports that kind of33behavior.3435Most importantly the extension must be shipped with a :file:`setup.py` file and36registered on PyPI. Also the development checkout link should work so37that people can easily install the development version into their38virtualenv without having to download the library by hand.3940Flask extensions must be licensed under a BSD, MIT or more liberal license41in order to be listed in the Flask Extension Registry. Keep in mind42that the Flask Extension Registry is a moderated place and libraries will43be reviewed upfront if they behave as required.4445"Hello Flaskext!"46-----------------4748So let's get started with creating such a Flask extension. The extension49we want to create here will provide very basic support for SQLite3.5051First we create the following folder structure::5253 flask-sqlite3/54 flask_sqlite3.py55 LICENSE56 README5758Here's the contents of the most important files:5960setup.py61````````6263The next file that is absolutely required is the :file:`setup.py` file which is64used to install your Flask extension. The following contents are65something you can work with::6667 """68 Flask-SQLite369 -------------7071 This is the description for that library72 """73 from setuptools import setup747576 setup(77 name='Flask-SQLite3',78 version='1.0',79 url='http://example.com/flask-sqlite3/',80 license='BSD',81 author='Your Name',82 author_email='your-email@example.com',83 description='Very short description',84 long_description=__doc__,85 py_modules=['flask_sqlite3'],86 # if you would be using a package instead use packages instead87 # of py_modules:88 # packages=['flask_sqlite3'],89 zip_safe=False,90 include_package_data=True,91 platforms='any',92 install_requires=[93 'Flask'94 ],95 classifiers=[96 'Environment :: Web Environment',97 'Intended Audience :: Developers',98 'License :: OSI Approved :: BSD License',99 'Operating System :: OS Independent',100 'Programming Language :: Python',101 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',102 'Topic :: Software Development :: Libraries :: Python Modules'103 ]104 )105106That's a lot of code but you can really just copy/paste that from existing107extensions and adapt.108109flask_sqlite3.py110````````````````111112Now this is where your extension code goes. But how exactly should such113an extension look like? What are the best practices? Continue reading114for some insight.115116Initializing Extensions117-----------------------118119Many extensions will need some kind of initialization step. For example,120consider an application that's currently connecting to SQLite like the121documentation suggests (:doc:`/patterns/sqlite3`). So how does the122extension know the name of the application object?123124Quite simple: you pass it to it.125126There are two recommended ways for an extension to initialize:127128initialization functions:129130 If your extension is called `helloworld` you might have a function131 called ``init_helloworld(app[, extra_args])`` that initializes the132 extension for that application. It could attach before / after133 handlers etc.134135classes:136137 Classes work mostly like initialization functions but can later beMerge pull request #3916 from greyli/fix-extdev-docsDavid Lordbefore adoptionaee3f3f
line 138why, one step back138 used to further change the behavior.Merge remote-tracking branch 'origin/1.1.x'David Lordbefore adoption6eeb912
lines 139–324why, one step back139140What to use depends on what you have in mind. For the SQLite 3 extension141we will use the class-based approach because it will provide users with an142object that handles opening and closing database connections.143144When designing your classes, it's important to make them easily reusable145at the module level. This means the object itself must not under any146circumstances store any application specific state and must be shareable147between different applications.148149The Extension Code150------------------151152Here's the contents of the `flask_sqlite3.py` for copy/paste::153154 import sqlite3155 from flask import current_app, _app_ctx_stack156157158 class SQLite3(object):159 def __init__(self, app=None):160 self.app = app161 if app is not None:162 self.init_app(app)163164 def init_app(self, app):165 app.config.setdefault('SQLITE3_DATABASE', ':memory:')166 app.teardown_appcontext(self.teardown)167168 def connect(self):169 return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])170171 def teardown(self, exception):172 ctx = _app_ctx_stack.top173 if hasattr(ctx, 'sqlite3_db'):174 ctx.sqlite3_db.close()175176 @property177 def connection(self):178 ctx = _app_ctx_stack.top179 if ctx is not None:180 if not hasattr(ctx, 'sqlite3_db'):181 ctx.sqlite3_db = self.connect()182 return ctx.sqlite3_db183184185So here's what these lines of code do:1861871. The ``__init__`` method takes an optional app object and, if supplied, will188 call ``init_app``.1892. The ``init_app`` method exists so that the ``SQLite3`` object can be190 instantiated without requiring an app object. This method supports the191 factory pattern for creating applications. The ``init_app`` will set the192 configuration for the database, defaulting to an in memory database if193 no configuration is supplied. In addition, the ``init_app`` method194 attaches the ``teardown`` handler.1953. Next, we define a ``connect`` method that opens a database connection.1964. Finally, we add a ``connection`` property that on first access opens197 the database connection and stores it on the context. This is also198 the recommended way to handling resources: fetch resources lazily the199 first time they are used.200201 Note here that we're attaching our database connection to the top202 application context via ``_app_ctx_stack.top``. Extensions should use203 the top context for storing their own information with a sufficiently204 complex name.205206So why did we decide on a class-based approach here? Because using our207extension looks something like this::208209 from flask import Flask210 from flask_sqlite3 import SQLite3211212 app = Flask(__name__)213 app.config.from_pyfile('the-config.cfg')214 db = SQLite3(app)215216You can then use the database from views like this::217218 @app.route('/')219 def show_all():220 cur = db.connection.cursor()221 cur.execute(...)222223Likewise if you are outside of a request you can use the database by224pushing an app context::225226 with app.app_context():227 cur = db.connection.cursor()228 cur.execute(...)229230At the end of the ``with`` block the teardown handles will be executed231automatically.232233Additionally, the ``init_app`` method is used to support the factory pattern234for creating apps::235236 db = SQLite3()237 # Then later on.238 app = create_app('the-config.cfg')239 db.init_app(app)240241Keep in mind that supporting this factory pattern for creating apps is required242for approved flask extensions (described below).243244.. admonition:: Note on ``init_app``245246 As you noticed, ``init_app`` does not assign ``app`` to ``self``. This247 is intentional! Class based Flask extensions must only store the248 application on the object when the application was passed to the249 constructor. This tells the extension: I am not interested in using250 multiple applications.251252 When the extension needs to find the current application and it does253 not have a reference to it, it must either use the254 :data:`~flask.current_app` context local or change the API in a way255 that you can pass the application explicitly.256257258Using _app_ctx_stack259--------------------260261In the example above, before every request, a ``sqlite3_db`` variable is262assigned to ``_app_ctx_stack.top``. In a view function, this variable is263accessible using the ``connection`` property of ``SQLite3``. During the264teardown of a request, the ``sqlite3_db`` connection is closed. By using265this pattern, the *same* connection to the sqlite3 database is accessible266to anything that needs it for the duration of the request.267268269Learn from Others270-----------------271272This documentation only touches the bare minimum for extension development.273If you want to learn more, it's a very good idea to check out existing extensions274on the `PyPI`_. If you feel lost there is still the `mailinglist`_ and the275`Discord server`_ to get some ideas for nice looking APIs. Especially if you do276something nobody before you did, it might be a very good idea to get some more277input. This not only generates useful feedback on what people might want from278an extension, but also avoids having multiple developers working in isolation279on pretty much the same problem.280281Remember: good API design is hard, so introduce your project on the282mailing list, and let other developers give you a helping hand with283designing the API.284285The best Flask extensions are extensions that share common idioms for the286API. And this can only work if collaboration happens early.287288Approved Extensions289-------------------290291Flask previously had the concept of approved extensions. These came with292some vetting of support and compatibility. While this list became too293difficult to maintain over time, the guidelines are still relevant to294all extensions maintained and developed today, as they help the Flask295ecosystem remain consistent and compatible.2962970. An approved Flask extension requires a maintainer. In the event an298 extension author would like to move beyond the project, the project299 should find a new maintainer and transfer access to the repository,300 documentation, PyPI, and any other services. If no maintainer301 is available, give access to the Pallets core team.3021. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*.303 It must provide exactly one package or module named304 ``flask_extension_name``.3052. The extension must be BSD or MIT licensed. It must be open source306 and publicly available.3073. The extension's API must have the following characteristics:308309 - It must support multiple applications running in the same Python310 process. Use ``current_app`` instead of ``self.app``, store311 configuration and state per application instance.312 - It must be possible to use the factory pattern for creating313 applications. Use the ``ext.init_app()`` pattern.3143154. From a clone of the repository, an extension with its dependencies316 must be installable with ``pip install -e .``.3175. It must ship a testing suite that can be invoked with ``tox -e py``318 or ``pytest``. If not using ``tox``, the test dependencies should be319 specified in a ``requirements.txt`` file. The tests must be part of320 the sdist distribution.3216. The documentation must use the ``flask`` theme from the322 `Official Pallets Themes`_. A link to the documentation or project323 website must be in the PyPI metadata or the readme.3247. For maximum compatibility, the extension should support the sameMerge pull request #4335 from pallets/drop-python-3.6David Lordbefore adoptionea93a52
lines 325–327why, one step back325 versions of Python that Flask supports. 3.7+ is recommended as of326 December 2021. Use ``python_requires=">= 3.7"`` in ``setup.py`` to327 indicate supported versions.Merge remote-tracking branch 'origin/1.1.x'David Lordbefore adoption6eeb912
lines 328–330why, one step back328329.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask330.. _mailinglist: https://mail.python.org/mailman/listinfo/flaskMerge pull request #3691 from greyli/update-discord-linksGrey Libefore adoptionf32f191
line 331why, one step back331.. _Discord server: https://discord.gg/palletsMerge remote-tracking branch 'origin/1.1.x'David Lordbefore adoption6eeb912
line 332why, one step back332.. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/