Skip to content
Myr

extensiondev.rst

This file

Path

docs/extensiondev.rst

303 lines · 12.5 KiB

Last changed by

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

History of this file

Take it

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

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 1–3why, one step back
1Flask Extension Development
2===========================3

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

line 4why, one step back
4.. currentmodule:: flask

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 5why, one step back
5

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 6–9why, one step back
6Extensions are extra packages that add functionality to a Flask
7application. 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.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 10why, one step back
10

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 11–13why, one step back
11This guide will show how to create a Flask extension, and some of the
12common patterns and requirements involved. Since extensions can do13anything, this guide won't be able to cover every possibility.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 14why, one step back
14

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 15–18why, one step back
15The best ways to learn about extensions are to look at how other
16extensions you use are written, and discuss with others. Discuss your17design ideas with others on our `Discord Chat`_ or18`GitHub Discussions`_.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 19why, one step back
19

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 20–22why, one step back
20The best extensions share common patterns, so that anyone familiar with
21using one extension won't feel completely lost with another. This can22only work if collaboration happens early.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 23–24why, one step back
23
24

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 25–26why, one step back
25Naming
26------

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 27why, one step back
27

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 28–31why, one step back
28A Flask extension typically has ``flask`` in its name as a prefix or
29suffix. If it wraps another library, it should include the library name30as well. This makes it easy to search for extensions, and makes their31purpose clearer.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 32why, one step back
32

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 33–38why, one step back
33A general Python packaging recommendation is that the install name from
34the 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.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 39why, one step back
39

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

line 40why, one step back
40Here are some example install and import names:

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 41why, one step back
41

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 42–45why, one step back
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``

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 46–47why, one step back
46
47

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 48–49why, one step back
48The Extension Class and Initialization
49--------------------------------------

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 50why, one step back
50

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 51–55why, one step back
51All extensions will need some entry point that initializes the
52extension 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.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 56why, one step back
56

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

line 57why, one step back
57.. code-block:: python

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 58why, one step back
58

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 59–62why, one step back
59 class HelloExtension:
60 def __init__(self, app=None):61 if app is not None:62 self.init_app(app)

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 63why, one step back
63

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 64–65why, one step back
64 def init_app(self, app):
65 app.before_request(...)

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 66why, one step back
66

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 67–70why, one step back
67It is important that the app is not stored on the extension, don't do
68``self.app = app``. The only time the extension should have direct69access to an app is during ``init_app``, otherwise it should use70:data:`current_app`.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 71why, one step back
71

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 72–75why, one step back
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.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 76why, one step back
76

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

line 77why, one step back
77.. code-block:: python

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 78why, one step back
78

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

line 79why, one step back
79 hello = HelloExtension()

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 80why, one step back
80

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 81–84why, one step back
81 def create_app():
82 app = Flask(__name__)83 hello.init_app(app)84 return app

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 85why, one step back
85

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 86–89why, one step back
86Above, the ``hello`` extension instance exists independently of the
87application. 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.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 90why, one step back
90

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 91–95why, one step back
91The :attr:`Flask.extensions` dict can be used to store a reference to
92the 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.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 96–97why, one step back
96
97

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 98–99why, one step back
98Adding Behavior
99---------------

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 100why, one step back
100

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 101–103why, one step back
101There are many ways that an extension can add behavior. Any setup
102methods that are available on the :class:`Flask` object can be used103during an extension's ``init_app`` method.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 104why, one step back
104

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 105–108why, one step back
105A common pattern is to use :meth:`~Flask.before_request` to initialize
106some data or a connection at the beginning of each request, then107:meth:`~Flask.teardown_request` to clean it up at the end. This can be108stored on :data:`g`, discussed more below.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 109why, one step back
109

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 110–113why, one step back
110A more lazy approach is to provide a method that initializes and caches
111the 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.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 114why, one step back
114

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 115–118why, one step back
115Besides doing something before and after every view, your extension
116might 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.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 119–120why, one step back
119
120

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 121–122why, one step back
121Configuration Techniques
122------------------------

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 123why, one step back
123

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 124–126why, one step back
124There can be multiple levels and sources of configuration for an
125extension. You should consider what parts of your extension fall into126each one.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 127why, one step back
127

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 128–148why, one step back
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.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 149why, one step back
149

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

line 150why, one step back
150The :class:`~flask.Flask` object itself uses all of these techniques.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 151why, one step back
151

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 152–153why, one step back
152It's up to you to decide what configuration is appropriate for your
153extension, based on what you need and what you want to support.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 154why, one step back
154

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 155–158why, one step back
155Configuration should not be changed after the application setup phase is
156complete and the server begins handling requests. Configuration is157global, any changes to it are not guaranteed to be visible to other158workers.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 159–160why, one step back
159
160

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 161–162why, one step back
161Data During a Request
162---------------------

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 163why, one step back
163

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 164–170why, one step back
164When writing a Flask application, the :data:`~flask.g` object is used to
165store 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.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 171why, one step back
171

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

line 172why, one step back
172.. code-block:: python

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 173why, one step back
173

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 174–175why, one step back
174 # an internal prefix with the extension name
175 g._hello_user_id = 2

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 176why, one step back
176

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 177–180why, one step back
177 # or an internal prefix as a namespace
178 from types import SimpleNamespace179 g._hello = SimpleNamespace()180 g._hello.user_id = 2

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 181why, one step back
181

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 182–186why, one step back
182The data in ``g`` lasts for an application context. An application
183context is active when a request context is, or when a CLI command is184run. If you're storing something that should be closed, use185:meth:`~flask.Flask.teardown_appcontext` to ensure that it gets closed186when the application context ends. If it should only be valid during a

Merge branch '2.2.x'David Lordbefore adoption73b9bac

line 187why, one step back
187request, or would not be used in the CLI outside a request, use

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

line 188why, one step back
188:meth:`~flask.Flask.teardown_request`.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 189–190why, one step back
189
190

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 191–192why, one step back
191Views and Models
192----------------

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 193why, one step back
193

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 194–198why, one step back
194Your extension views might want to interact with specific models in your
195database, or some other extension or data connected to your application.196For example, let's consider a ``Flask-SimpleBlog`` extension that works197with Flask-SQLAlchemy to provide a ``Post`` model and views to write198and read posts.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 199why, one step back
199

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 200–203why, one step back
200The ``Post`` model needs to subclass the Flask-SQLAlchemy ``db.Model``
201object, but that's only available once you've created an instance of202that extension, not when your extension is defining its views. So how203can the view code, defined before the model exists, access the model?

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 204why, one step back
204

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 205–207why, one step back
205One method could be to use :doc:`views`. During ``__init__``, create
206the model, then create the views by passing the model to the view207class's :meth:`~views.View.as_view` method.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 208why, one step back
208

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

line 209why, one step back
209.. code-block:: python

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 210why, one step back
210

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 211–213why, one step back
211 class PostAPI(MethodView):
212 def __init__(self, model):213 self.model = model

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 214why, one step back
214

Merge branch '2.2.x'David Lordbefore adoption7464e17

line 215why, one step back
215 def get(self, id):

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 216–217why, one step back
216 post = self.model.query.get(id)
217 return jsonify(post.to_json())

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 218why, one step back
218

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 219–223why, one step back
219 class BlogExtension:
220 def __init__(self, db):221 class Post(db.Model):222 id = db.Column(primary_key=True)223 title = db.Column(db.String, nullable=False)

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 224why, one step back
224

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

line 225why, one step back
225 self.post_model = Post

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 226why, one step back
226

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 227–228why, one step back
227 def init_app(self, app):
228 api_view = PostAPI.as_view(model=self.post_model)

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 229why, one step back
229

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 230–233why, one step back
230 db = SQLAlchemy()
231 blog = BlogExtension(db)232 db.init_app(app)233 blog.init_app(app)

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 234why, one step back
234

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 235–238why, one step back
235Another technique could be to use an attribute on the extension, such as
236``self.post_model`` from above. Add the extension to ``app.extensions``237in ``init_app``, then access238``current_app.extensions["simple_blog"].post_model`` from views.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 239why, one step back
239

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 240–243why, one step back
240You may also want to provide base classes so that users can provide
241their own ``Post`` model that conforms to the API your extension242expects. So they could implement ``class Post(blog.BasePost)``, then243set it as ``blog.post_model``.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 244why, one step back
244

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 245–250why, one step back
245As you can see, this can get a bit complex. Unfortunately, there's no
246perfect solution here, only different strategies and tradeoffs depending247on your needs and how much customization you want to offer. Luckily,248this sort of resource dependency is not a common need for most249extensions. Remember, if you need help with design, ask on our250`Discord Chat`_ or `GitHub Discussions`_.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 251–252why, one step back
251
252

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 253–254why, one step back
253Recommended Extension Guidelines
254--------------------------------

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

line 255why, one step back
255

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 256–260why, one step back
256Flask previously had the concept of "approved extensions", where the
257Flask maintainers evaluated the quality, support, and compatibility of258the extensions before listing them. While the list became too difficult259to maintain over time, the guidelines are still relevant to all260extensions maintained and developed today, as they help the Flask

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 261–262why, one step back
261ecosystem remain consistent and compatible.
262

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 263–269why, one step back
2631. An extension requires a maintainer. In the event an extension author
264 would like to move beyond the project, the project should find a new265 maintainer and transfer access to the repository, documentation,266 PyPI, and any other services. The `Pallets-Eco`_ organization on267 GitHub allows for community maintenance with oversight from the268 Pallets maintainers.2692. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 270–271why, one step back
270 It must provide exactly one package or module named
271 ``flask_extension_name``.

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 272–275why, one step back
2723. The extension must use an open source license. The Python web
273 ecosystem tends to prefer BSD or MIT. It must be open source and274 publicly available.2754. The extension's API must have the following characteristics:

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 276–282why, one step back
276
277 - It must support multiple applications running in the same Python278 process. Use ``current_app`` instead of ``self.app``, store279 configuration and state per application instance.280 - It must be possible to use the factory pattern for creating281 applications. Use the ``ext.init_app()`` pattern.282

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 283–295why, one step back
2835. From a clone of the repository, an extension with its dependencies
284 must be installable in editable mode with ``pip install -e .``.2856. It must ship tests that can be invoked with a common tool like286 ``tox -e py``, ``nox -s test`` or ``pytest``. If not using ``tox``,287 the test dependencies should be specified in a requirements file.288 The tests must be part of the sdist distribution.2897. A link to the documentation or project website must be in the PyPI290 metadata or the readme. The documentation should use the Flask theme291 from the `Official Pallets Themes`_.2928. The extension's dependencies should not use upper bounds or assume293 any particular version scheme, but should use lower bounds to294 indicate minimum compatibility support. For example,295 ``sqlalchemy>=1.4``.

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

lines 296–297why, one step back
2969. Indicate the versions of Python supported using ``python_requires=">=version"``.
297 Flask itself supports Python >=3.8 as of April 2023, but this will update over time.

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

lines 298–299why, one step back
298
299.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoptiona25d234

lines 300–301why, one step back
300.. _Discord Chat: https://discord.gg/pallets
301.. _GitHub Discussions: https://github.com/pallets/flask/discussions

pin os and python version in rtd buildDavid Lordbefore adoption93a7f08

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

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

line 303why, one step back
303.. _Pallets-Eco: https://github.com/pallets-eco