signals.rst
This file
Path
docs/signals.rst
167 lines · 6.0 KiB
Last changed by
Merge pull request #5077 from EtiennePelletier/masterDavid Lordbefore adoption0c5f18a
History of this fileTake 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 back1Signals2=======3Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6
lines 4–6why, one step back4Signals are a lightweight way to notify subscribers of certain events during the5lifecycle of the application and each request. When an event occurs, it emits the6signal, which calls each subscriber.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 7why, one step back7Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6
lines 8–9why, one step back8Signals are implemented by the `Blinker`_ library. See its documentation for detailed9information. Flask provides some built-in signals. Extensions may provide their own.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 10why, one step back10Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6
lines 11–17why, one step back11Many signals mirror Flask's decorator-based callbacks with similar names. For example,12the :data:`.request_started` signal is similar to the :meth:`~.Flask.before_request`13decorator. The advantage of signals over handlers is that they can be subscribed to14temporarily, and can't directly affect the application. This is useful for testing,15metrics, auditing, and more. For example, if you want to know what templates were16rendered at what parts of what requests, there is a signal that will notify you of that17information.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 18–19why, one step back1819Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6
lines 20–21why, one step back20Core Signals21------------pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 22why, one step back22Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6
lines 23–26why, one step back23See :ref:`core-signals-list` for a list of all built-in signals. The :doc:`lifecycle`24page also describes the order that signals and decorators execute.2526pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 27–101why, one step back27Subscribing to Signals28----------------------2930To subscribe to a signal, you can use the31:meth:`~blinker.base.Signal.connect` method of a signal. The first32argument is the function that should be called when the signal is emitted,33the optional second argument specifies a sender. To unsubscribe from a34signal, you can use the :meth:`~blinker.base.Signal.disconnect` method.3536For all core Flask signals, the sender is the application that issued the37signal. When you subscribe to a signal, be sure to also provide a sender38unless you really want to listen for signals from all applications. This is39especially true if you are developing an extension.4041For example, here is a helper context manager that can be used in a unit test42to determine which templates were rendered and what variables were passed43to the template::4445 from flask import template_rendered46 from contextlib import contextmanager4748 @contextmanager49 def captured_templates(app):50 recorded = []51 def record(sender, template, context, **extra):52 recorded.append((template, context))53 template_rendered.connect(record, app)54 try:55 yield recorded56 finally:57 template_rendered.disconnect(record, app)5859This can now easily be paired with a test client::6061 with captured_templates(app) as templates:62 rv = app.test_client().get('/')63 assert rv.status_code == 20064 assert len(templates) == 165 template, context = templates[0]66 assert template.name == 'index.html'67 assert len(context['items']) == 106869Make sure to subscribe with an extra ``**extra`` argument so that your70calls don't fail if Flask introduces new arguments to the signals.7172All the template rendering in the code issued by the application `app`73in the body of the ``with`` block will now be recorded in the `templates`74variable. Whenever a template is rendered, the template object as well as75context are appended to it.7677Additionally there is a convenient helper method78(:meth:`~blinker.base.Signal.connected_to`) that allows you to79temporarily subscribe a function to a signal with a context manager on80its own. Because the return value of the context manager cannot be81specified that way, you have to pass the list in as an argument::8283 from flask import template_rendered8485 def captured_templates(app, recorded, **extra):86 def record(sender, template, context):87 recorded.append((template, context))88 return template_rendered.connected_to(record, app)8990The example above would then look like this::9192 templates = []93 with captured_templates(app, templates, **extra):94 ...95 template, context = templates[0]9697Creating Signals98----------------99100If you want to use signals in your own application, you can use the101blinker library directly. The most common use case are named signals in aMerge pull request #5077 from EtiennePelletier/masterDavid Lordbefore adoption0c5f18a
line 102why, one step back102custom :class:`~blinker.base.Namespace`. This is what is recommendedpin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 103–156why, one step back103most of the time::104105 from blinker import Namespace106 my_signals = Namespace()107108Now you can create new signals like this::109110 model_saved = my_signals.signal('model-saved')111112The name for the signal here makes it unique and also simplifies113debugging. You can access the name of the signal with the114:attr:`~blinker.base.NamedSignal.name` attribute.115116.. _signals-sending:117118Sending Signals119---------------120121If you want to emit a signal, you can do so by calling the122:meth:`~blinker.base.Signal.send` method. It accepts a sender as first123argument and optionally some keyword arguments that are forwarded to the124signal subscribers::125126 class Model(object):127 ...128129 def save(self):130 model_saved.send(self)131132Try to always pick a good sender. If you have a class that is emitting a133signal, pass ``self`` as sender. If you are emitting a signal from a random134function, you can pass ``current_app._get_current_object()`` as sender.135136.. admonition:: Passing Proxies as Senders137138 Never pass :data:`~flask.current_app` as sender to a signal. Use139 ``current_app._get_current_object()`` instead. The reason for this is140 that :data:`~flask.current_app` is a proxy and not the real application141 object.142143144Signals and Flask's Request Context145-----------------------------------146147Signals fully support :doc:`reqcontext` when receiving signals.148Context-local variables are consistently available between149:data:`~flask.request_started` and :data:`~flask.request_finished`, so you can150rely on :class:`flask.g` and others as needed. Note the limitations described151in :ref:`signals-sending` and the :data:`~flask.request_tearing_down` signal.152153154Decorator Based Signal Subscriptions155------------------------------------156Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6
line 157why, one step back157You can also easily subscribe to signals by using thepin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 158–167why, one step back158:meth:`~blinker.base.NamedSignal.connect_via` decorator::159160 from flask import template_rendered161162 @template_rendered.connect_via(app)163 def when_template_rendered(sender, template, context, **extra):164 print(f'Template {template.name} is rendered with {context}')165166167.. _blinker: https://pypi.org/project/blinker/