rewrite extension development docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 0a01248 · Browse files · 2 files·+233 added−255 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+233 added−255 removed
- other:+233 added−255 removed
Provenance
- Commit
b46bfcf- Tree
6f87e45- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
0a01248
2 files changed+233 added−255 removed
modified:docs/extensiondev.rst+229 added-251 removed
1 Flask Extension Development2 ===========================3 4-Flask, being a microframework, often requires some repetitive steps to get5-a third party library working. Many such extensions are already available6-on `PyPI`_.4+.. currentmodule:: flask5 8-If you want to create your own Flask extension for something that does not9-exist yet, this guide to extension development will help you get your10-extension running in no time and to feel like users would expect your11-extension to behave.6+Extensions are extra packages that add functionality to a Flask7+application. While `PyPI`_ contains many Flask extensions, you may not8+find one that fits your need. If this is the case, you can create your9+own, and publish it for others to use as well.10 13-Anatomy of an Extension14------------------------11+This guide will show how to create a Flask extension, and some of the12+common patterns and requirements involved. Since extensions can do13+anything, this guide won't be able to cover every possibility.14 16-Extensions are all located in a package called ``flask_something``17-where "something" is the name of the library you want to bridge. So for18-example if you plan to add support for a library named `simplexml` to19-Flask, you would name your extension's package ``flask_simplexml``.15+The best ways to learn about extensions are to look at how other16+extensions you use are written, and discuss with others. Discuss your17+design ideas with others on our `Discord Chat`_ or18+`GitHub Discussions`_.19 21-The name of the actual extension (the human readable name) however would22-be something like "Flask-SimpleXML". Make sure to include the name23-"Flask" somewhere in that name and that you check the capitalization.24-This is how users can then register dependencies to your extension in25-their :file:`setup.py` files.20+The best extensions share common patterns, so that anyone familiar with21+using one extension won't feel completely lost with another. This can22+only work if collaboration happens early.23 27-But what do extensions look like themselves? An extension has to ensure28-that it works with multiple Flask application instances at once. This is29-a requirement because many people will use patterns like the30-:doc:`/patterns/appfactories` pattern to create their application as31-needed to aid unittests and to support multiple configurations. Because32-of that it is crucial that your application supports that kind of33-behavior.24 35-Most importantly the extension must be shipped with a :file:`setup.py` file and36-registered on PyPI. Also the development checkout link should work so37-that people can easily install the development version into their38-virtualenv without having to download the library by hand.25+Naming26+------27 40-Flask extensions must be licensed under a BSD, MIT or more liberal license41-in order to be listed in the Flask Extension Registry. Keep in mind42-that the Flask Extension Registry is a moderated place and libraries will43-be reviewed upfront if they behave as required.28+A Flask extension typically has ``flask`` in its name as a prefix or29+suffix. If it wraps another library, it should include the library name30+as well. This makes it easy to search for extensions, and makes their31+purpose clearer.32 45-"Hello Flaskext!"46------------------33+A general Python packaging recommendation is that the install name from34+the package index and the name used in ``import`` statements should be35+related. The import name is lowercase, with words separated by36+underscores (``_``). The install name is either lower case or title37+case, with words separated by dashes (``-``). If it wraps another38+library, prefer using the same case as that library's name.39 48-So let's get started with creating such a Flask extension. The extension49-we want to create here will provide very basic support for SQLite3.40+Here are some example install and import names:41 51-First we create the following folder structure::42+- ``Flask-Name`` imported as ``flask_name``43+- ``flask-name-lower`` imported as ``flask_name_lower``44+- ``Flask-ComboName`` imported as ``flask_comboname``45+- ``Name-Flask`` imported as ``name_flask``46 53- flask-sqlite3/54- flask_sqlite3.py55- LICENSE56- README47 58-Here's the contents of the most important files:48+The Extension Class and Initialization49+--------------------------------------50 60-setup.py61-````````51+All extensions will need some entry point that initializes the52+extension with the application. The most common pattern is to create a53+class that represents the extension's configuration and behavior, with54+an ``init_app`` method to apply the extension instance to the given55+application instance.56 63-The next file that is absolutely required is the :file:`setup.py` file which is64-used to install your Flask extension. The following contents are65-something you can work with::57+.. code-block:: python58 67- """68- Flask-SQLite369- -------------59+ class HelloExtension:60+ def __init__(self, app=None):61+ if app is not None:62+ self.init_app(app)63 71- This is the description for that library72- """73- from setuptools import setup64+ def init_app(self, app):65+ app.before_request(...)66 67+It is important that the app is not stored on the extension, don't do68+``self.app = app``. The only time the extension should have direct69+access to an app is during ``init_app``, otherwise it should use70+:data:`current_app`.71 76- 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- )72+This allows the extension to support the application factory pattern,73+avoids circular import issues when importing the extension instance74+elsewhere in a user's code, and makes testing with different75+configurations easier.76 106-That's a lot of code but you can really just copy/paste that from existing107-extensions and adapt.77+.. code-block:: python78 109-flask_sqlite3.py110-````````````````79+ hello = HelloExtension()80 112-Now this is where your extension code goes. But how exactly should such113-an extension look like? What are the best practices? Continue reading114-for some insight.81+ def create_app():82+ app = Flask(__name__)83+ hello.init_app(app)84+ return app85 116-Initializing Extensions117------------------------86+Above, the ``hello`` extension instance exists independently of the87+application. This means that other modules in a user's project can do88+``from project import hello`` and use the extension in blueprints before89+the app exists.90 119-Many extensions will need some kind of initialization step. For example,120-consider an application that's currently connecting to SQLite like the121-documentation suggests (:doc:`/patterns/sqlite3`). So how does the122-extension know the name of the application object?91+The :attr:`Flask.extensions` dict can be used to store a reference to92+the extension on the application, or some other state specific to the93+application. Be aware that this is a single namespace, so use a name94+unique to your extension, such as the extension's name without the95+"flask" prefix.96 124-Quite simple: you pass it to it.97 126-There are two recommended ways for an extension to initialize:98+Adding Behavior99+---------------100 128-initialization functions:101+There are many ways that an extension can add behavior. Any setup102+methods that are available on the :class:`Flask` object can be used103+during an extension's ``init_app`` method.104 130- 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.105+A common pattern is to use :meth:`~Flask.before_request` to initialize106+some data or a connection at the beginning of each request, then107+:meth:`~Flask.teardown_request` to clean it up at the end. This can be108+stored on :data:`g`, discussed more below.109 135-classes:110+A more lazy approach is to provide a method that initializes and caches111+the data or connection. For example, a ``ext.get_db`` method could112+create a database connection the first time it's called, so that a view113+that doesn't use the database doesn't create a connection.114 137- Classes work mostly like initialization functions but can later be138- used to further change the behavior.115+Besides doing something before and after every view, your extension116+might want to add some specific views as well. In this case, you could117+define a :class:`Blueprint`, then call :meth:`~Flask.register_blueprint`118+during ``init_app`` to add the blueprint to the app.119 140-What to use depends on what you have in mind. For the SQLite 3 extension141-we will use the class-based approach because it will provide users with an142-object that handles opening and closing database connections.120 144-When designing your classes, it's important to make them easily reusable145-at the module level. This means the object itself must not under any146-circumstances store any application specific state and must be shareable147-between different applications.121+Configuration Techniques122+------------------------123 149-The Extension Code150-------------------124+There can be multiple levels and sources of configuration for an125+extension. You should consider what parts of your extension fall into126+each one.127 152-Here's the contents of the `flask_sqlite3.py` for copy/paste::128+- Configuration per application instance, through ``app.config``129+ values. This is configuration that could reasonably change for each130+ deployment of an application. A common example is a URL to an131+ external resource, such as a database. Configuration keys should132+ start with the extension's name so that they don't interfere with133+ other extensions.134+- Configuration per extension instance, through ``__init__``135+ arguments. This configuration usually affects how the extension136+ is used, such that it wouldn't make sense to change it per137+ deployment.138+- Configuration per extension instance, through instance attributes139+ and decorator methods. It might be more ergonomic to assign to140+ ``ext.value``, or use a ``@ext.register`` decorator to register a141+ function, after the extension instance has been created.142+- Global configuration through class attributes. Changing a class143+ attribute like ``Ext.connection_class`` can customize default144+ behavior without making a subclass. This could be combined145+ per-extension configuration to override defaults.146+- Subclassing and overriding methods and attributes. Making the API of147+ the extension itself something that can be overridden provides a148+ very powerful tool for advanced customization.149 154- import sqlite3155- from flask import current_app, _app_ctx_stack150+The :class:`~flask.Flask` object itself uses all of these techniques.151 152+It's up to you to decide what configuration is appropriate for your153+extension, based on what you need and what you want to support.154 158- class SQLite3(object):159- def __init__(self, app=None):160- self.app = app161- if app is not None:162- self.init_app(app)155+Configuration should not be changed after the application setup phase is156+complete and the server begins handling requests. Configuration is157+global, any changes to it are not guaranteed to be visible to other158+workers.159 164- def init_app(self, app):165- app.config.setdefault('SQLITE3_DATABASE', ':memory:')166- app.teardown_appcontext(self.teardown)160 168- def connect(self):169- return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])161+Data During a Request162+---------------------163 171- def teardown(self, exception):172- ctx = _app_ctx_stack.top173- if hasattr(ctx, 'sqlite3_db'):174- ctx.sqlite3_db.close()164+When writing a Flask application, the :data:`~flask.g` object is used to165+store information during a request. For example the166+:doc:`tutorial <tutorial/database>` stores a connection to a SQLite167+database as ``g.db``. Extensions can also use this, with some care.168+Since ``g`` is a single global namespace, extensions must use unique169+names that won't collide with user data. For example, use the extension170+name as a prefix, or as a namespace.171 176- @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_db172+.. code-block:: python173 174+ # an internal prefix with the extension name175+ g._hello_user_id = 2176 185-So here's what these lines of code do:177+ # or an internal prefix as a namespace178+ from types import SimpleNamespace179+ g._hello = SimpleNamespace()180+ g._hello.user_id = 2181 187-1. The ``__init__`` method takes an optional app object and, if supplied, will188- call ``init_app``.189-2. 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.195-3. Next, we define a ``connect`` method that opens a database connection.196-4. 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.182+The data in ``g`` lasts for an application context. An application183+context is active when a request context is, or when a CLI command is184+run. If you're storing something that should be closed, use185+:meth:`~flask.Flask.teardown_appcontext` to ensure that it gets closed186+when the application context ends. If it should only be valid during a187+request, or would not be used in the CLI outside a reqeust, use188+:meth:`~flask.Flask.teardown_request`.189 201- 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.190+An older technique for storing context data was to store it on191+``_app_ctx_stack.top`` or ``_request_ctx_stack.top``. However, this just192+moves the same namespace collision problem elsewhere (although less193+likely) and modifies objects that are very internal to Flask's194+operations. Prefer storing data under a unique name in ``g``.195 206-So why did we decide on a class-based approach here? Because using our207-extension looks something like this::196 209- from flask import Flask210- from flask_sqlite3 import SQLite3197+Views and Models198+----------------199 212- app = Flask(__name__)213- app.config.from_pyfile('the-config.cfg')214- db = SQLite3(app)200+Your extension views might want to interact with specific models in your201+database, or some other extension or data connected to your application.202+For example, let's consider a ``Flask-SimpleBlog`` extension that works203+with Flask-SQLAlchemy to provide a ``Post`` model and views to write204+and read posts.205 216-You can then use the database from views like this::206+The ``Post`` model needs to subclass the Flask-SQLAlchemy ``db.Model``207+object, but that's only available once you've created an instance of208+that extension, not when your extension is defining its views. So how209+can the view code, defined before the model exists, access the model?210 218- @app.route('/')219- def show_all():220- cur = db.connection.cursor()221- cur.execute(...)211+One method could be to use :doc:`views`. During ``__init__``, create212+the model, then create the views by passing the model to the view213+class's :meth:`~views.View.as_view` method.214 223-Likewise if you are outside of a request you can use the database by224-pushing an app context::215+.. code-block:: python216 226- with app.app_context():227- cur = db.connection.cursor()228- cur.execute(...)217+ class PostAPI(MethodView):218+ def __init__(self, model):219+ self.model = model220 230-At the end of the ``with`` block the teardown handles will be executed231-automatically.221+ def get(id):222+ post = self.model.query.get(id)223+ return jsonify(post.to_json())224 233-Additionally, the ``init_app`` method is used to support the factory pattern234-for creating apps::225+ class BlogExtension:226+ def __init__(self, db):227+ class Post(db.Model):228+ id = db.Column(primary_key=True)229+ title = db.Column(db.String, nullable=False)230 236- db = SQLite3()237- # Then later on.238- app = create_app('the-config.cfg')239- db.init_app(app)231+ self.post_model = Post232 241-Keep in mind that supporting this factory pattern for creating apps is required242-for approved flask extensions (described below).233+ def init_app(self, app):234+ api_view = PostAPI.as_view(model=self.post_model)235 244-.. admonition:: Note on ``init_app``236+ db = SQLAlchemy()237+ blog = BlogExtension(db)238+ db.init_app(app)239+ blog.init_app(app)240 246- 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.241+Another technique could be to use an attribute on the extension, such as242+``self.post_model`` from above. Add the extension to ``app.extensions``243+in ``init_app``, then access244+``current_app.extensions["simple_blog"].post_model`` from views.245 252- 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.246+You may also want to provide base classes so that users can provide247+their own ``Post`` model that conforms to the API your extension248+expects. So they could implement ``class Post(blog.BasePost)``, then249+set it as ``blog.post_model``.250 251+As you can see, this can get a bit complex. Unfortunately, there's no252+perfect solution here, only different strategies and tradeoffs depending253+on your needs and how much customization you want to offer. Luckily,254+this sort of resource dependency is not a common need for most255+extensions. Remember, if you need help with design, ask on our256+`Discord Chat`_ or `GitHub Discussions`_.257 258-Using _app_ctx_stack259---------------------258 261-In the example above, before every request, a ``sqlite3_db`` variable is262-assigned to ``_app_ctx_stack.top``. In a view function, this variable is263-accessible using the ``connection`` property of ``SQLite3``. During the264-teardown of a request, the ``sqlite3_db`` connection is closed. By using265-this pattern, the *same* connection to the sqlite3 database is accessible266-to anything that needs it for the duration of the request.259+Recommended Extension Guidelines260+--------------------------------261 268-269-Learn from Others270------------------271-272-This documentation only touches the bare minimum for extension development.273-If you want to learn more, it's a very good idea to check out existing extensions274-on `PyPI`_. If you feel lost there is `Discord Chat`_ or275-`GitHub Discussions`_ to get some ideas for nice looking APIs. Especially if you do276-something nobody before you did, it might be a very good idea to get some more277-input. This not only generates useful feedback on what people might want from278-an extension, but also avoids having multiple developers working in isolation279-on pretty much the same problem.280-281-Remember: good API design is hard, so introduce your project on282-`Discord Chat`_ or `GitHub Discussions`_, and let other developers give283-you a helping hand with designing the API.284-285-The best Flask extensions are extensions that share common idioms for the286-API. And this can only work if collaboration happens early.287-288-Approved Extensions289--------------------290-291-Flask previously had the concept of approved extensions. These came with292-some vetting of support and compatibility. While this list became too293-difficult to maintain over time, the guidelines are still relevant to294-all extensions maintained and developed today, as they help the Flask262+Flask previously had the concept of "approved extensions", where the263+Flask maintainers evaluated the quality, support, and compatibility of264+the extensions before listing them. While the list became too difficult265+to maintain over time, the guidelines are still relevant to all266+extensions maintained and developed today, as they help the Flask267 ecosystem remain consistent and compatible.268 297-0. 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.302-1. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*.269+1. An extension requires a maintainer. In the event an extension author270+ would like to move beyond the project, the project should find a new271+ maintainer and transfer access to the repository, documentation,272+ PyPI, and any other services. The `Pallets-Eco`_ organization on273+ GitHub allows for community maintenance with oversight from the274+ Pallets maintainers.275+2. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*.276 It must provide exactly one package or module named277 ``flask_extension_name``.278+3. The extension must use an open source license. The Python web305-2. The extension must be BSD or MIT licensed. It must be open source306- and publicly available.307-3. The extension's API must have the following characteristics:279+ ecosystem tends to prefer BSD or MIT. It must be open source and280+ publicly available.281+4. The extension's API must have the following characteristics:282 283 - It must support multiple applications running in the same Python284 process. Use ``current_app`` instead of ``self.app``, store285 configuration and state per application instance.286 - It must be possible to use the factory pattern for creating287 applications. Use the ``ext.init_app()`` pattern.288 315-4. From a clone of the repository, an extension with its dependencies316- must be installable with ``pip install -e .``.317-5. 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.321-6. 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.324-7. For maximum compatibility, the extension should support the same325- 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.289+5. From a clone of the repository, an extension with its dependencies290+ must be installable in editable mode with ``pip install -e .``.291+6. It must ship tests that can be invoked with a common tool like292+ ``tox -e py``, ``nox -s test`` or ``pytest``. If not using ``tox``,293+ the test dependencies should be specified in a requirements file.294+ The tests must be part of the sdist distribution.295+7. A link to the documentation or project website must be in the PyPI296+ metadata or the readme. The documentation should use the Flask theme297+ from the `Official Pallets Themes`_.298+8. The extension's dependencies should not use upper bounds or assume299+ any particular version scheme, but should use lower bounds to300+ indicate minimum compatibility support. For example,301+ ``sqlalchemy>=1.4``.302+9. Indicate the versions of Python supported using303+ ``python_requires=">=version"``. Flask itself supports Python >=3.7304+ as of December 2021, but this will update over time.305 306 .. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask307 .. _Discord Chat: https://discord.gg/pallets308 .. _GitHub Discussions: https://github.com/pallets/flask/discussions309 .. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/310+.. _Pallets-Eco: https://github.com/pallets-ecomodified:docs/extensions.rst+4 added-4 removed
37 unmodified lines38 39 Building Extensions40 -------------------41 42-While the `PyPI <pypi_>`_ contains many Flask extensions, you may43-not find an extension that fits your need. If this is the case, you can44-create your own. Read :doc:`/extensiondev` to develop your own Flask45-extension.42+While `PyPI <pypi_>`_ contains many Flask extensions, you may not find43+an extension that fits your need. If this is the case, you can create44+your own, and publish it for others to use as well. Read45+:doc:`extensiondev` to develop your own Flask extension.46 47 48 .. _pypi: https://pypi.org/search/?c=Framework+%3A%3A+Flask