| 1 |
======= |
| 2 |
Signals |
| 3 |
======= |
| 4 |
|
| 5 |
.. module:: django.dispatch |
| 6 |
:synopsis: Signal dispatch |
| 7 |
|
| 8 |
Django includes a "signal dispatcher" which helps decoupled applications get |
| 9 |
notified when actions occur elsewhere in the framework. In a nutshell, signals |
| 10 |
allow certain *senders* to notify a set of *receivers* that some action has |
| 11 |
taken place. They're especially useful when many pieces of code may be |
| 12 |
interested in the same events. |
| 13 |
|
| 14 |
For example, a third-party app can register to be notified of settings |
| 15 |
changes:: |
| 16 |
|
| 17 |
from django.apps import AppConfig |
| 18 |
from django.core.signals import setting_changed |
| 19 |
|
| 20 |
|
| 21 |
def my_callback(sender, **kwargs): |
| 22 |
print("Setting changed!") |
| 23 |
|
| 24 |
|
| 25 |
class MyAppConfig(AppConfig): |
| 26 |
... |
| 27 |
|
| 28 |
def ready(self): |
| 29 |
setting_changed.connect(my_callback) |
| 30 |
|
| 31 |
Django's :doc:`built-in signals </ref/signals>` let user code get notified of |
| 32 |
certain actions. |
| 33 |
|
| 34 |
You can also define and send your own custom signals. See |
| 35 |
:ref:`defining-and-sending-signals` below. |
| 36 |
|
| 37 |
.. warning:: |
| 38 |
|
| 39 |
Signals give the appearance of loose coupling, but they can quickly lead to |
| 40 |
code that is hard to understand, adjust and debug. |
| 41 |
|
| 42 |
Where possible you should opt for directly calling the handling code, |
| 43 |
rather than dispatching via a signal. |
| 44 |
|
| 45 |
Listening to signals |
| 46 |
==================== |
| 47 |
|
| 48 |
To receive a signal, register a *receiver* function using the |
| 49 |
:meth:`Signal.connect` method. The receiver function is called when the signal |
| 50 |
is sent. All of the signal's receiver functions are called one at a time, in |
| 51 |
the order they were registered. |
| 52 |
|
| 53 |
.. method:: Signal.connect(receiver, sender=None, weak=True, dispatch_uid=None) |
| 54 |
|
| 55 |
:param receiver: The callback function which will be connected to this |
| 56 |
signal. See :ref:`receiver-functions` for more information. |
| 57 |
|
| 58 |
:param sender: Specifies a particular sender to receive signals from. See |
| 59 |
:ref:`connecting-to-specific-signals` for more information. |
| 60 |
|
| 61 |
:param weak: Django stores signal handlers as weak references by |
| 62 |
default. Thus, if your receiver is a local function, it may be |
| 63 |
garbage collected. To prevent this, pass ``weak=False`` when you call |
| 64 |
the signal's ``connect()`` method. |
| 65 |
|
| 66 |
:param dispatch_uid: A unique identifier for a signal receiver in cases |
| 67 |
where duplicate signals may be sent. See |
| 68 |
:ref:`preventing-duplicate-signals` for more information. |
| 69 |
|
| 70 |
Let's see how this works by registering a signal that |
| 71 |
gets called after each HTTP request is finished. We'll be connecting to the |
| 72 |
:data:`~django.core.signals.request_finished` signal. |
| 73 |
|
| 74 |
.. _receiver-functions: |
| 75 |
|
| 76 |
Receiver functions |
| 77 |
------------------ |
| 78 |
|
| 79 |
First, we need to define a receiver function. A receiver can be any Python |
| 80 |
function or method:: |
| 81 |
|
| 82 |
def my_callback(sender, **kwargs): |
| 83 |
print("Request finished!") |
| 84 |
|
| 85 |
Notice that the function takes a ``sender`` argument, along with wildcard |
| 86 |
keyword arguments (``**kwargs``); all signal handlers must take these arguments. |
| 87 |
|
| 88 |
We'll look at senders :ref:`a bit later <connecting-to-specific-signals>`, but |
| 89 |
right now look at the ``**kwargs`` argument. All signals send keyword |
| 90 |
arguments, and may change those keyword arguments at any time. In the case of |
| 91 |
:data:`~django.core.signals.request_finished`, it's documented as sending no |
| 92 |
arguments, which means we might be tempted to write our signal handling as |
| 93 |
``my_callback(sender)``. |
| 94 |
|
| 95 |
This would be wrong -- in fact, Django will throw an error if you do so. That's |
| 96 |
because at any point arguments could get added to the signal and your receiver |
| 97 |
must be able to handle those new arguments. |
| 98 |
|
| 99 |
Receivers may also be asynchronous functions, with the same signature but |
| 100 |
declared using ``async def``:: |
| 101 |
|
| 102 |
async def my_callback(sender, **kwargs): |
| 103 |
await asyncio.sleep(5) |
| 104 |
print("Request finished!") |
| 105 |
|
| 106 |
Signals can be sent either synchronously or asynchronously, and receivers will |
| 107 |
automatically be adapted to the correct call-style. See :ref:`sending signals |
| 108 |
<sending-signals>` for more information. |
| 109 |
|
| 110 |
.. _connecting-receiver-functions: |
| 111 |
|
| 112 |
Connecting receiver functions |
| 113 |
----------------------------- |
| 114 |
|
| 115 |
There are two ways you can connect a receiver to a signal. You can take the |
| 116 |
manual connect route:: |
| 117 |
|
| 118 |
from django.core.signals import request_finished |
| 119 |
|
| 120 |
request_finished.connect(my_callback) |
| 121 |
|
| 122 |
Alternatively, you can use a :func:`receiver` decorator: |
| 123 |
|
| 124 |
.. function:: receiver(signal, **kwargs) |
| 125 |
|
| 126 |
:param signal: A signal or a list of signals to connect a function to. |
| 127 |
:param kwargs: Wildcard keyword arguments to pass to a |
| 128 |
:ref:`function <receiver-functions>`. |
| 129 |
|
| 130 |
Here's how you connect with the decorator:: |
| 131 |
|
| 132 |
from django.core.signals import request_finished |
| 133 |
from django.dispatch import receiver |
| 134 |
|
| 135 |
|
| 136 |
@receiver(request_finished) |
| 137 |
def my_callback(sender, **kwargs): |
| 138 |
print("Request finished!") |
| 139 |
|
| 140 |
Now, our ``my_callback`` function will be called each time a request finishes. |
| 141 |
|
| 142 |
.. admonition:: Where should this code live? |
| 143 |
|
| 144 |
Strictly speaking, signal handling and registration code can live anywhere |
| 145 |
you like, although it's recommended to avoid the application's root module |
| 146 |
and its ``models`` module to minimize side-effects of importing code. |
| 147 |
|
| 148 |
In practice, signal handlers are usually defined in a ``signals`` |
| 149 |
submodule of the application they relate to. Signal receivers are |
| 150 |
connected in the :meth:`~django.apps.AppConfig.ready` method of your |
| 151 |
application :ref:`configuration class <configuring-applications-ref>`. If |
| 152 |
you're using the :func:`receiver` decorator, import the ``signals`` |
| 153 |
submodule inside :meth:`~django.apps.AppConfig.ready`, this will implicitly |
| 154 |
connect signal handlers:: |
| 155 |
|
| 156 |
from django.apps import AppConfig |
| 157 |
from django.core.signals import request_finished |
| 158 |
|
| 159 |
|
| 160 |
class MyAppConfig(AppConfig): |
| 161 |
... |
| 162 |
|
| 163 |
def ready(self): |
| 164 |
# Implicitly connect signal handlers decorated with @receiver. |
| 165 |
from . import signals |
| 166 |
|
| 167 |
# Explicitly connect a signal handler. |
| 168 |
request_finished.connect(signals.my_callback) |
| 169 |
|
| 170 |
.. note:: |
| 171 |
|
| 172 |
The :meth:`~django.apps.AppConfig.ready` method may be executed more than |
| 173 |
once during testing, so you may want to :ref:`guard your signals from |
| 174 |
duplication <preventing-duplicate-signals>`, especially if you're planning |
| 175 |
to send them within tests. |
| 176 |
|
| 177 |
.. _connecting-to-specific-signals: |
| 178 |
|
| 179 |
Connecting to signals sent by specific senders |
| 180 |
---------------------------------------------- |
| 181 |
|
| 182 |
Some signals get sent many times, but you'll only be interested in receiving a |
| 183 |
certain subset of those signals. For example, consider the |
| 184 |
:data:`django.db.models.signals.pre_save` signal sent before a model gets saved. |
| 185 |
Most of the time, you don't need to know when *any* model gets saved -- just |
| 186 |
when one *specific* model is saved. |
| 187 |
|
| 188 |
In these cases, you can register to receive signals sent only by particular |
| 189 |
senders. In the case of :data:`django.db.models.signals.pre_save`, the sender |
| 190 |
will be the model class being saved, so you can indicate that you only want |
| 191 |
signals sent by some model:: |
| 192 |
|
| 193 |
from django.db.models.signals import pre_save |
| 194 |
from django.dispatch import receiver |
| 195 |
from myapp.models import MyModel |
| 196 |
|
| 197 |
|
| 198 |
@receiver(pre_save, sender=MyModel) |
| 199 |
def my_handler(sender, **kwargs): ... |
| 200 |
|
| 201 |
The ``my_handler`` function will only be called when an instance of ``MyModel`` |
| 202 |
is saved. |
| 203 |
|
| 204 |
Different signals use different objects as their senders; you'll need to consult |
| 205 |
the :doc:`built-in signal documentation </ref/signals>` for details of each |
| 206 |
particular signal. |
| 207 |
|
| 208 |
.. _preventing-duplicate-signals: |
| 209 |
|
| 210 |
Preventing duplicate signals |
| 211 |
---------------------------- |
| 212 |
|
| 213 |
In some circumstances, the code connecting receivers to signals may run |
| 214 |
multiple times. This can cause your receiver function to be registered more |
| 215 |
than once, and thus called as many times for a signal event. For example, the |
| 216 |
:meth:`~django.apps.AppConfig.ready` method may be executed more than once |
| 217 |
during testing. More generally, this occurs everywhere your project imports the |
| 218 |
module where you define the signals, because signal registration runs as many |
| 219 |
times as it is imported. |
| 220 |
|
| 221 |
If this behavior is problematic (such as when using signals to |
| 222 |
send an email whenever a model is saved), pass a unique identifier as |
| 223 |
the ``dispatch_uid`` argument to identify your receiver function. This |
| 224 |
identifier will usually be a string, although any hashable object will |
| 225 |
suffice. The end result is that your receiver function will only be |
| 226 |
bound to the signal once for each unique ``dispatch_uid`` value:: |
| 227 |
|
| 228 |
from django.core.signals import request_finished |
| 229 |
|
| 230 |
request_finished.connect(my_callback, dispatch_uid="my_unique_identifier") |
| 231 |
|
| 232 |
.. _defining-and-sending-signals: |
| 233 |
|
| 234 |
Defining and sending signals |
| 235 |
============================ |
| 236 |
|
| 237 |
Your applications can take advantage of the signal infrastructure and provide |
| 238 |
its own signals. |
| 239 |
|
| 240 |
.. admonition:: When to use custom signals |
| 241 |
|
| 242 |
Signals are implicit function calls which make debugging harder. If the |
| 243 |
sender and receiver of your custom signal are both within your project, |
| 244 |
you're better off using an explicit function call. |
| 245 |
|
| 246 |
Defining signals |
| 247 |
---------------- |
| 248 |
|
| 249 |
.. class:: Signal() |
| 250 |
|
| 251 |
All signals are :class:`django.dispatch.Signal` instances. |
| 252 |
|
| 253 |
For example:: |
| 254 |
|
| 255 |
import django.dispatch |
| 256 |
|
| 257 |
pizza_done = django.dispatch.Signal() |
| 258 |
|
| 259 |
This declares a ``pizza_done`` signal. |
| 260 |
|
| 261 |
.. _sending-signals: |
| 262 |
|
| 263 |
Sending signals |
| 264 |
--------------- |
| 265 |
|
| 266 |
There are two ways to send signals synchronously in Django. |
| 267 |
|
| 268 |
.. method:: Signal.send(sender, **kwargs) |
| 269 |
.. method:: Signal.send_robust(sender, **kwargs) |
| 270 |
|
| 271 |
Signals may also be sent asynchronously. |
| 272 |
|
| 273 |
.. method:: Signal.asend(sender, **kwargs) |
| 274 |
.. method:: Signal.asend_robust(sender, **kwargs) |
| 275 |
|
| 276 |
To send a signal, call either :meth:`Signal.send`, :meth:`Signal.send_robust`, |
| 277 |
:meth:`await Signal.asend()<Signal.asend>`, or |
| 278 |
:meth:`await Signal.asend_robust() <Signal.asend_robust>`. You must provide the |
| 279 |
``sender`` argument (which is a class most of the time) and may provide as many |
| 280 |
other keyword arguments as you like. |
| 281 |
|
| 282 |
For example, here's how sending our ``pizza_done`` signal might look:: |
| 283 |
|
| 284 |
class PizzaStore: |
| 285 |
... |
| 286 |
|
| 287 |
def send_pizza(self, toppings, size): |
| 288 |
pizza_done.send(sender=self.__class__, toppings=toppings, size=size) |
| 289 |
... |
| 290 |
|
| 291 |
All four methods return a list of tuple pairs ``[(receiver, response), ...]``, |
| 292 |
representing the list of called receiver functions and their response values. |
| 293 |
|
| 294 |
``send()`` differs from ``send_robust()`` in how exceptions raised by receiver |
| 295 |
functions are handled. ``send()`` does *not* catch any exceptions raised by |
| 296 |
receivers; it simply allows errors to propagate. Thus not all receivers may |
| 297 |
be notified of a signal in the face of an error. |
| 298 |
|
| 299 |
``send_robust()`` catches all errors derived from Python's ``Exception`` class, |
| 300 |
and ensures all receivers are notified of the signal. If an error occurs, the |
| 301 |
error instance is returned in the tuple pair for the receiver that raised the error. |
| 302 |
|
| 303 |
The tracebacks are present on the ``__traceback__`` attribute of the errors |
| 304 |
returned when calling ``send_robust()``. |
| 305 |
|
| 306 |
``asend()`` is similar to ``send()``, but it is a coroutine that must be |
| 307 |
awaited:: |
| 308 |
|
| 309 |
async def asend_pizza(self, toppings, size): |
| 310 |
await pizza_done.asend(sender=self.__class__, toppings=toppings, size=size) |
| 311 |
... |
| 312 |
|
| 313 |
Whether synchronous or asynchronous, receivers will be correctly adapted to |
| 314 |
whether ``send()`` or ``asend()`` is used. Synchronous receivers will be |
| 315 |
called using :func:`~.sync_to_async` when invoked via ``asend()``. Asynchronous |
| 316 |
receivers will be called using :func:`~.async_to_sync` when invoked via |
| 317 |
``send()``. Similar to the :ref:`case for middleware <async_performance>`, |
| 318 |
there is a small performance cost to adapting receivers in this way. Note that |
| 319 |
in order to reduce the number of sync/async calling-style switches within a |
| 320 |
``send()`` or ``asend()`` call, the receivers are grouped by whether or not |
| 321 |
they are async before being called. This means that an asynchronous receiver |
| 322 |
registered before a synchronous receiver may be executed after the synchronous |
| 323 |
receiver. In addition, async receivers are executed concurrently using |
| 324 |
``asyncio.gather()``. |
| 325 |
|
| 326 |
All built-in signals, except those in the async request-response cycle, are |
| 327 |
dispatched using :meth:`Signal.send`. |
| 328 |
|
| 329 |
Disconnecting signals |
| 330 |
===================== |
| 331 |
|
| 332 |
.. method:: Signal.disconnect(receiver=None, sender=None, dispatch_uid=None) |
| 333 |
|
| 334 |
To disconnect a receiver from a signal, call :meth:`Signal.disconnect`. The |
| 335 |
arguments are as described in :meth:`.Signal.connect`. The method returns |
| 336 |
``True`` if a receiver was disconnected and ``False`` if not. When ``sender`` |
| 337 |
is passed as a lazy reference to ``<app label>.<model>``, this method always |
| 338 |
returns ``None``. |
| 339 |
|
| 340 |
The ``receiver`` argument indicates the registered receiver to disconnect. It |
| 341 |
may be ``None`` if ``dispatch_uid`` is used to identify the receiver. |