Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

305 lines · 12.6 KiB

Last changed by

merge app and request context (#5812)David Lordbefore adoptionadf3636

History of this file

Take it

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

Merge branch '2.2.x'David Lordbefore adoption7464e17

lines 1–69why, one step back
1Flask Extension Development
2===========================34.. currentmodule:: flask56Extensions are extra packages that add functionality to a Flask7application. While `PyPI`_ contains many Flask extensions, you may not8find one that fits your need. If this is the case, you can create your9own, and publish it for others to use as well.1011This guide will show how to create a Flask extension, and some of the12common patterns and requirements involved. Since extensions can do13anything, this guide won't be able to cover every possibility.1415The best ways to learn about extensions are to look at how other16extensions you use are written, and discuss with others. Discuss your17design ideas with others on our `Discord Chat`_ or18`GitHub Discussions`_.1920The best extensions share common patterns, so that anyone familiar with21using one extension won't feel completely lost with another. This can22only work if collaboration happens early.232425Naming26------2728A Flask extension typically has ``flask`` in its name as a prefix or29suffix. If it wraps another library, it should include the library name30as well. This makes it easy to search for extensions, and makes their31purpose clearer.3233A general Python packaging recommendation is that the install name from34the package index and the name used in ``import`` statements should be35related. The import name is lowercase, with words separated by36underscores (``_``). The install name is either lower case or title37case, with words separated by dashes (``-``). If it wraps another38library, prefer using the same case as that library's name.3940Here are some example install and import names:4142- ``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``464748The Extension Class and Initialization49--------------------------------------5051All extensions will need some entry point that initializes the52extension with the application. The most common pattern is to create a53class that represents the extension's configuration and behavior, with54an ``init_app`` method to apply the extension instance to the given55application instance.5657.. code-block:: python5859 class HelloExtension:60 def __init__(self, app=None):61 if app is not None:62 self.init_app(app)6364 def init_app(self, app):65 app.before_request(...)6667It is important that the app is not stored on the extension, don't do68``self.app = app``. The only time the extension should have direct69access to an app is during ``init_app``, otherwise it should use

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 70why, one step back
70:data:`.current_app`.

Merge branch '2.2.x'David Lordbefore adoption7464e17

lines 71–107why, one step back
71
72This allows the extension to support the application factory pattern,73avoids circular import issues when importing the extension instance74elsewhere in a user's code, and makes testing with different75configurations easier.7677.. code-block:: python7879 hello = HelloExtension()8081 def create_app():82 app = Flask(__name__)83 hello.init_app(app)84 return app8586Above, the ``hello`` extension instance exists independently of the87application. This means that other modules in a user's project can do88``from project import hello`` and use the extension in blueprints before89the app exists.9091The :attr:`Flask.extensions` dict can be used to store a reference to92the extension on the application, or some other state specific to the93application. Be aware that this is a single namespace, so use a name94unique to your extension, such as the extension's name without the95"flask" prefix.969798Adding Behavior99---------------100101There are many ways that an extension can add behavior. Any setup102methods that are available on the :class:`Flask` object can be used103during an extension's ``init_app`` method.104105A common pattern is to use :meth:`~Flask.before_request` to initialize106some data or a connection at the beginning of each request, then107:meth:`~Flask.teardown_request` to clean it up at the end. This can be

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 108why, one step back
108stored on :data:`.g`, discussed more below.

Merge branch '2.2.x'David Lordbefore adoption7464e17

lines 109–181why, one step back
109
110A more lazy approach is to provide a method that initializes and caches111the data or connection. For example, a ``ext.get_db`` method could112create a database connection the first time it's called, so that a view113that doesn't use the database doesn't create a connection.114115Besides doing something before and after every view, your extension116might want to add some specific views as well. In this case, you could117define a :class:`Blueprint`, then call :meth:`~Flask.register_blueprint`118during ``init_app`` to add the blueprint to the app.119120121Configuration Techniques122------------------------123124There can be multiple levels and sources of configuration for an125extension. You should consider what parts of your extension fall into126each one.127128- 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.149150The :class:`~flask.Flask` object itself uses all of these techniques.151152It's up to you to decide what configuration is appropriate for your153extension, based on what you need and what you want to support.154155Configuration should not be changed after the application setup phase is156complete and the server begins handling requests. Configuration is157global, any changes to it are not guaranteed to be visible to other158workers.159160161Data During a Request162---------------------163164When writing a Flask application, the :data:`~flask.g` object is used to165store information during a request. For example the166:doc:`tutorial <tutorial/database>` stores a connection to a SQLite167database as ``g.db``. Extensions can also use this, with some care.168Since ``g`` is a single global namespace, extensions must use unique169names that won't collide with user data. For example, use the extension170name as a prefix, or as a namespace.171172.. code-block:: python173174 # an internal prefix with the extension name175 g._hello_user_id = 2176177 # or an internal prefix as a namespace178 from types import SimpleNamespace179 g._hello = SimpleNamespace()180 g._hello.user_id = 2181

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 182–187why, one step back
182The data in ``g`` lasts for an application context. An application context is
183active during a request, CLI command, or ``with app.app_context()`` block. If184you're storing something that should be closed, use185:meth:`~flask.Flask.teardown_appcontext` to ensure that it gets closed when the186app context ends. If it should only be valid during a request, or would not be187used in the CLI outside a request, use :meth:`~flask.Flask.teardown_request`.

Merge branch '2.2.x'David Lordbefore adoption7464e17

lines 188–294why, one step back
188
189190Views and Models191----------------192193Your extension views might want to interact with specific models in your194database, or some other extension or data connected to your application.195For example, let's consider a ``Flask-SimpleBlog`` extension that works196with Flask-SQLAlchemy to provide a ``Post`` model and views to write197and read posts.198199The ``Post`` model needs to subclass the Flask-SQLAlchemy ``db.Model``200object, but that's only available once you've created an instance of201that extension, not when your extension is defining its views. So how202can the view code, defined before the model exists, access the model?203204One method could be to use :doc:`views`. During ``__init__``, create205the model, then create the views by passing the model to the view206class's :meth:`~views.View.as_view` method.207208.. code-block:: python209210 class PostAPI(MethodView):211 def __init__(self, model):212 self.model = model213214 def get(self, id):215 post = self.model.query.get(id)216 return jsonify(post.to_json())217218 class BlogExtension:219 def __init__(self, db):220 class Post(db.Model):221 id = db.Column(primary_key=True)222 title = db.Column(db.String, nullable=False)223224 self.post_model = Post225226 def init_app(self, app):227 api_view = PostAPI.as_view(model=self.post_model)228229 db = SQLAlchemy()230 blog = BlogExtension(db)231 db.init_app(app)232 blog.init_app(app)233234Another technique could be to use an attribute on the extension, such as235``self.post_model`` from above. Add the extension to ``app.extensions``236in ``init_app``, then access237``current_app.extensions["simple_blog"].post_model`` from views.238239You may also want to provide base classes so that users can provide240their own ``Post`` model that conforms to the API your extension241expects. So they could implement ``class Post(blog.BasePost)``, then242set it as ``blog.post_model``.243244As you can see, this can get a bit complex. Unfortunately, there's no245perfect solution here, only different strategies and tradeoffs depending246on your needs and how much customization you want to offer. Luckily,247this sort of resource dependency is not a common need for most248extensions. Remember, if you need help with design, ask on our249`Discord Chat`_ or `GitHub Discussions`_.250251252Recommended Extension Guidelines253--------------------------------254255Flask previously had the concept of "approved extensions", where the256Flask maintainers evaluated the quality, support, and compatibility of257the extensions before listing them. While the list became too difficult258to maintain over time, the guidelines are still relevant to all259extensions maintained and developed today, as they help the Flask260ecosystem remain consistent and compatible.2612621. An extension requires a maintainer. In the event an extension author263 would like to move beyond the project, the project should find a new264 maintainer and transfer access to the repository, documentation,265 PyPI, and any other services. The `Pallets-Eco`_ organization on266 GitHub allows for community maintenance with oversight from the267 Pallets maintainers.2682. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*.269 It must provide exactly one package or module named270 ``flask_extension_name``.2713. The extension must use an open source license. The Python web272 ecosystem tends to prefer BSD or MIT. It must be open source and273 publicly available.2744. The extension's API must have the following characteristics:275276 - It must support multiple applications running in the same Python277 process. Use ``current_app`` instead of ``self.app``, store278 configuration and state per application instance.279 - It must be possible to use the factory pattern for creating280 applications. Use the ``ext.init_app()`` pattern.2812825. From a clone of the repository, an extension with its dependencies283 must be installable in editable mode with ``pip install -e .``.2846. It must ship tests that can be invoked with a common tool like285 ``tox -e py``, ``nox -s test`` or ``pytest``. If not using ``tox``,286 the test dependencies should be specified in a requirements file.287 The tests must be part of the sdist distribution.2887. A link to the documentation or project website must be in the PyPI289 metadata or the readme. The documentation should use the Flask theme290 from the `Official Pallets Themes`_.2918. The extension's dependencies should not use upper bounds or assume292 any particular version scheme, but should use lower bounds to293 indicate minimum compatibility support. For example,294 ``sqlalchemy>=1.4``.

Merge pull request #5072 from pallets/drop-py37David Lordbefore adoptionb4345cb

line 295why, one step back
2959. Indicate the versions of Python supported using ``python_requires=">=version"``.

drop end of life python versions (#5731)David Lordbefore adoptiona5f9742

lines 296–298why, one step back
296 Flask and Pallets policy is to support all Python versions that are not
297 within six months of end of life (EOL). See Python's `EOL calendar`_ for298 timing.

Merge branch '2.2.x'David Lordbefore adoption7464e17

lines 299–304why, one step back
299
300.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask301.. _Discord Chat: https://discord.gg/pallets302.. _GitHub Discussions: https://github.com/pallets/flask/discussions303.. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/304.. _Pallets-Eco: https://github.com/pallets-eco

drop end of life python versions (#5731)David Lordbefore adoptiona5f9742

line 305why, one step back
305.. _EOL calendar: https://devguide.python.org/versions/