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
Provenance
- Commit
c360f00- Tree
d856937- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
e0712b4
3 files changed+208 added−0 removed
modified:docs/api.rst+2 added
353 unmodified lines354 355 Signals356 -------357 358+.. when modifying this list, also update the one in signals.rst359+360 .. versionadded:: 0.6361 362 .. data:: signals_available363 43 unmodified linesmodified:docs/contents.rst.inc+1 added
13 unmodified lines14 tutorial/index15 testing16 errorhandling17 config18+ signals19 shell20 patterns/index21 deploying/index22 becomingbig29 unmodified linesadded:docs/signals.rst+205 added
1+.. _signals:2+3+Signals4+=======5+6+.. versionadded:: 0.67+8+Starting with Flask 0.6, there is integrated support for signalling in9+Flask. This support is provided by the excellent `blinker`_ library and10+will gracefully fall back if it is not available.11+12+What are signals? Signals help you decouple applications by sending13+notifications when actions occur elsewhere in the core framework or14+another Flask extensions. In short, signals allow certain senders to15+notify subscribers that something happened.16+17+Flask comes with a couple of signals and other extensions might provide18+more. Also keep in mind that signals are intended to notify subscribers19+and should not encourage subscribers to modify data. You will notice that20+there are signals that appear to do the same thing like some of the21+builtin decorators do (eg: :data:`~flask.request_started` is very similar22+to :meth:`~flask.Flask.before_request`). There are however difference in23+how they work. The core :meth:`~flask.Flask.before_request` handler for24+example is executed in a specific order and is able to abort the request25+early by returning a response. In contrast all signal handlers are26+executed in undefined order and do not modify any data.27+28+The big advantage of signals over handlers is that you can safely29+subscribe to them for the split of a second. These temporary30+subscriptions are helpful for unittesting for example. Say you want to31+know what templates were rendered as part of a request: signals allow you32+to do exactly that.33+34+Subscribing to Signals35+----------------------36+37+To subscribe to a signal, you can use the38+:meth:`~blinker.base.Signal.connect` method of a signal. The first39+argument is the function that should be called when the signal is emitted,40+the optional second argument specifies a sender. To unsubscribe from a41+signal, you can use the :meth:`~blinker.base.Signal.disconnect` method.42+43+For all core Flask signals, the sender is the application that issued the44+signal. This however might not be true for Flask extensions, so consult45+the documentation when subscribing to signals.46+47+Additionally there is a convenient helper method that allows you to48+temporarily subscribe a function to a signal. This is especially helpful49+for unittests (:meth:`~blinker.base.Signal.temporarily_connected_to`).50+This has to be used in combination with the `with` statement.51+52+Here for example a helper context manager that can be used to figure out53+in a unittest which templates were rendered and what variables were passed54+to the template::55+56+ from flask import template_rendered57+ from contextlib import contextmanager58+59+ @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)69+70+This can now easily be paired with a test client::71+72+ 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']) == 1079+80+All the template rendering in the code, the `with` block wraps will now be81+recorded in the `templates` variable. Whenever a template is rendered,82+the template object as well as context is appended to it.83+84+Creating Signals85+----------------86+87+If you want to use signals in your own application, you can use the88+blinker library directly. The most common use case are named signals in a89+custom :class:`~blinker.base.Namespace`.. This is what is recommended90+most of the time::91+92+ from blinker import Namespace93+ my_signals = Namespace()94+95+Now you can create new signals like this::96+97+ model_saved = my_signals.signal('model-saved')98+99+The name for the signal here makes it unique and also simplifies100+debugging. You can access the name of the signal with the101+:attr:`~blinker.base.NamedSignal.name` attribute.102+103+.. admonition:: For Extension Developers104+105+ 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.108+109+Sending Signals110+---------------111+112+If you want to emit a signal, you can do so by calling the113+:meth:`~blinker.base.Signal.send` method. It accepts a sender as first114+argument and optionally some keyword arguments that are forwarded to the115+signal subscribers::116+117+ class Model(object):118+ ...119+120+ def save(self):121+ model_saved.send(self)122+123+Try to always pick a good sender. If you have a class that is emitting a124+signal, pass `self` as sender. If you emitting a signal from a random125+function, you can pass ``current_app._get_current_object()`` as sender.126+127+.. admonition:: Passing Proxies as Senders128+129+ 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.133+134+Core Signals135+------------136+137+.. when modifying this list, also update the one in api.rst138+139+The following signals exist in Flask:140+141+.. data:: flask.template_rendered142+ :noindex:143+144+ 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`).147+148+ Example subscriber::149+150+ 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)154+155+ from flask import request_started156+ request_started.connect(log_template_renders)157+158+.. data:: flask.request_started159+ :noindex:160+161+ 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`.165+166+ Example subscriber::167+168+ def log_request(sender):169+ sender.logger.debug('Request context is set up')170+171+ from flask import request_started172+ request_started.connect(log_request)173+174+.. data:: flask.request_finished175+ :noindex:176+177+ This signal is sent right before the response is sent to the client.178+ It is passed the response to be sent named `response`.179+180+ Example subscriber::181+182+ def log_response(sender, response):183+ sender.logger.debug('Request context is about to close down. '184+ 'Response: %s', response)185+186+ from flask import request_finished187+ request_finished.connect(log_response)188+189+.. data:: flask.got_request_exception190+ :noindex:191+192+ 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`.196+197+ Example subscriber::198+199+ def log_exception(sender, exception):200+ sender.logger.debug('Got exception during processing: %s', exception)201+202+ from flask import got_request_exception203+ got_request_exception.connect(log_exception)204+205+.. _blinker: http://pypi.python.org/pypi/blinker