Skip to content
Myr

Added signal documentation

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent e0712b4 · Browse files · 3 files+208 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+208 added−0 removed

  • other:+208 added−0 removed

3 files+208 added−0 removed

modified:docs/api.rst+2 added
353 unmodified lines
354355Signals356-------357358.. when modifying this list, also update the one in signals.rst359360.. versionadded:: 0.6361362.. data:: signals_available363
43 unmodified lines
modified:docs/contents.rst.inc+1 added
13 unmodified lines
14 tutorial/index15 testing16 errorhandling17 config18 signals19 shell20 patterns/index21 deploying/index22 becomingbig
29 unmodified lines
added:docs/signals.rst+205 added
1.. _signals:23Signals4=======56.. versionadded:: 0.678Starting with Flask 0.6, there is integrated support for signalling in9Flask. This support is provided by the excellent `blinker`_ library and10will gracefully fall back if it is not available.1112What are signals? Signals help you decouple applications by sending13notifications when actions occur elsewhere in the core framework or14another Flask extensions. In short, signals allow certain senders to15notify subscribers that something happened.1617Flask comes with a couple of signals and other extensions might provide18more. Also keep in mind that signals are intended to notify subscribers19and should not encourage subscribers to modify data. You will notice that20there are signals that appear to do the same thing like some of the21builtin decorators do (eg: :data:`~flask.request_started` is very similar22to :meth:`~flask.Flask.before_request`). There are however difference in23how they work. The core :meth:`~flask.Flask.before_request` handler for24example is executed in a specific order and is able to abort the request25early by returning a response. In contrast all signal handlers are26executed in undefined order and do not modify any data.2728The big advantage of signals over handlers is that you can safely29subscribe to them for the split of a second. These temporary30subscriptions are helpful for unittesting for example. Say you want to31know what templates were rendered as part of a request: signals allow you32to do exactly that.3334Subscribing to Signals35----------------------3637To subscribe to a signal, you can use the38:meth:`~blinker.base.Signal.connect` method of a signal. The first39argument is the function that should be called when the signal is emitted,40the optional second argument specifies a sender. To unsubscribe from a41signal, you can use the :meth:`~blinker.base.Signal.disconnect` method.4243For all core Flask signals, the sender is the application that issued the44signal. This however might not be true for Flask extensions, so consult45the documentation when subscribing to signals.4647Additionally there is a convenient helper method that allows you to48temporarily subscribe a function to a signal. This is especially helpful49for unittests (:meth:`~blinker.base.Signal.temporarily_connected_to`).50This has to be used in combination with the `with` statement.5152Here for example a helper context manager that can be used to figure out53in a unittest which templates were rendered and what variables were passed54to the template::5556 from flask import template_rendered57 from contextlib import contextmanager5859 @contextmanager60 def captured_templates():61 recorded = []62 def record(template, context):63 recorded.append((template, context))64 template_rendered.connect(record)65 try:66 yield templates67 finally:68 template_rendered.disconnect(record)6970This can now easily be paired with a test client::7172 with captured_templates() as templates:73 rv = app.test_client().get('/')74 assert rv.status_code == 20075 assert len(templates) == 176 template, context = templates[0]77 assert template.name == 'index.html'78 assert len(context['items']) == 107980All the template rendering in the code, the `with` block wraps will now be81recorded in the `templates` variable. Whenever a template is rendered,82the template object as well as context is appended to it.8384Creating Signals85----------------8687If you want to use signals in your own application, you can use the88blinker library directly. The most common use case are named signals in a89custom :class:`~blinker.base.Namespace`.. This is what is recommended90most of the time::9192 from blinker import Namespace93 my_signals = Namespace()9495Now you can create new signals like this::9697 model_saved = my_signals.signal('model-saved')9899The name for the signal here makes it unique and also simplifies100debugging. You can access the name of the signal with the101:attr:`~blinker.base.NamedSignal.name` attribute.102103.. admonition:: For Extension Developers104105 If you are writing a Flask extension and you to gracefully degrade for106 missing blinker installations, you can do so by using the107 :class:`flask.signals.Namespace` class.108109Sending Signals110---------------111112If you want to emit a signal, you can do so by calling the113:meth:`~blinker.base.Signal.send` method. It accepts a sender as first114argument and optionally some keyword arguments that are forwarded to the115signal subscribers::116117 class Model(object):118 ...119120 def save(self):121 model_saved.send(self)122123Try to always pick a good sender. If you have a class that is emitting a124signal, pass `self` as sender. If you emitting a signal from a random125function, you can pass ``current_app._get_current_object()`` as sender.126127.. admonition:: Passing Proxies as Senders128129 Never pass :data:`~flask.current_app` as sender to a signal. Use130 ``current_app._get_current_object()`` instead. The reason for this is131 that :data:`~flask.current_app` is a proxy and not the real application132 object.133134Core Signals135------------136137.. when modifying this list, also update the one in api.rst138139The following signals exist in Flask:140141.. data:: flask.template_rendered142 :noindex:143144 This signal is sent when a template was successfully rendered. The145 signal is invoked with the instance of the template as `template`146 and the context as dictionary (named `context`).147148 Example subscriber::149150 def log_template_renders(sender, template, context):151 sender.logger.debug('Rendering template "%s" with context %s',152 template.name or 'string template',153 context)154155 from flask import request_started156 request_started.connect(log_template_renders)157158.. data:: flask.request_started159 :noindex:160161 This signal is sent before any request processing started but when the162 request context was set up. Because the request context is already163 bound, the subscriber can access the request with the standard global164 proxies such as :class:`~flask.request`.165166 Example subscriber::167168 def log_request(sender):169 sender.logger.debug('Request context is set up')170171 from flask import request_started172 request_started.connect(log_request)173174.. data:: flask.request_finished175 :noindex:176177 This signal is sent right before the response is sent to the client.178 It is passed the response to be sent named `response`.179180 Example subscriber::181182 def log_response(sender, response):183 sender.logger.debug('Request context is about to close down. '184 'Response: %s', response)185186 from flask import request_finished187 request_finished.connect(log_response)188189.. data:: flask.got_request_exception190 :noindex:191192 This signal is sent when an exception happens during request processing.193 It is sent *before* the standard exception handling kicks in and even194 in debug mode, where no exception handling happens. The exception195 itself is passed to the subscriber as `exception`.196197 Example subscriber::198199 def log_exception(sender, exception):200 sender.logger.debug('Got exception during processing: %s', exception)201202 from flask import got_request_exception203 got_request_exception.connect(log_exception)204205.. _blinker: http://pypi.python.org/pypi/blinker