signals.rst
This file
Path
docs/signals.rst
166 lines · 6.0 KiB
Last changed by
merge app and request context (#5812)David Lordbefore adoptionadf3636
History of this fileTake it
1Signals2=======34Signals 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.78Signals are implemented by the `Blinker`_ library. See its documentation for detailed9information. Flask provides some built-in signals. Extensions may provide their own.1011Many 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.181920Core Signals21------------2223See :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.252627Subscribing 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 a102custom :class:`~blinker.base.Namespace`. This is what is recommended103most 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-----------------------------------146147Context-local proxies are available between :data:`~flask.request_started` and148:data:`~flask.request_finished`, so you can rely on :class:`flask.g` and others149as needed. Note the limitations described in :ref:`signals-sending` and the150:data:`~flask.request_tearing_down` signal.151152153Decorator Based Signal Subscriptions154------------------------------------155156You can also easily subscribe to signals by using the157:meth:`~blinker.base.NamedSignal.connect_via` decorator::158159 from flask import template_rendered160161 @template_rendered.connect_via(app)162 def when_template_rendered(sender, template, context, **extra):163 print(f'Template {template.name} is rendered with {context}')164165166.. _blinker: https://pypi.org/project/blinker/