2008-08-26 19:04:52 +00:00
|
|
|
=======
|
|
|
|
Signals
|
|
|
|
=======
|
|
|
|
|
|
|
|
.. module:: django.dispatch
|
|
|
|
:synopsis: Signal dispatch
|
|
|
|
|
2021-06-29 12:07:12 +00:00
|
|
|
Django includes a "signal dispatcher" which helps decoupled applications get
|
|
|
|
notified when actions occur elsewhere in the framework. In a nutshell, signals
|
|
|
|
allow certain *senders* to notify a set of *receivers* that some action has
|
|
|
|
taken place. They're especially useful when many pieces of code may be
|
2008-08-26 19:04:52 +00:00
|
|
|
interested in the same events.
|
|
|
|
|
2022-10-22 16:52:53 +00:00
|
|
|
For example, a third-party app can register to be notified of settings
|
|
|
|
changes::
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2022-10-22 16:52:53 +00:00
|
|
|
from django.apps import AppConfig
|
|
|
|
from django.core.signals import setting_changed
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2023-02-28 19:53:28 +00:00
|
|
|
|
2022-10-22 16:52:53 +00:00
|
|
|
def my_callback(sender, **kwargs):
|
|
|
|
print("Setting changed!")
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2023-02-28 19:53:28 +00:00
|
|
|
|
2022-10-22 16:52:53 +00:00
|
|
|
class MyAppConfig(AppConfig):
|
|
|
|
...
|
2010-01-13 11:07:16 +00:00
|
|
|
|
2022-10-22 16:52:53 +00:00
|
|
|
def ready(self):
|
|
|
|
setting_changed.connect(my_callback)
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2022-10-22 16:52:53 +00:00
|
|
|
Django's :doc:`built-in signals </ref/signals>` let user code get notified of
|
|
|
|
certain actions.
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2022-10-22 16:52:53 +00:00
|
|
|
You can also define and send your own custom signals. See
|
|
|
|
:ref:`defining-and-sending-signals` below.
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2022-10-22 16:52:53 +00:00
|
|
|
.. warning::
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2022-10-22 16:52:53 +00:00
|
|
|
Signals give the appearance of loose coupling, but they can quickly lead to
|
|
|
|
code that is hard to understand, adjust and debug.
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2022-10-22 16:52:53 +00:00
|
|
|
Where possible you should opt for directly calling the handling code,
|
|
|
|
rather than dispatching via a signal.
|
2008-08-26 19:04:52 +00:00
|
|
|
|
|
|
|
Listening to signals
|
|
|
|
====================
|
|
|
|
|
2016-11-24 10:50:39 +00:00
|
|
|
To receive a signal, register a *receiver* function using the
|
|
|
|
:meth:`Signal.connect` method. The receiver function is called when the signal
|
2019-10-28 12:31:23 +00:00
|
|
|
is sent. All of the signal's receiver functions are called one at a time, in
|
|
|
|
the order they were registered.
|
2010-10-24 08:52:00 +00:00
|
|
|
|
2015-07-27 12:35:21 +00:00
|
|
|
.. method:: Signal.connect(receiver, sender=None, weak=True, dispatch_uid=None)
|
2012-06-08 10:00:51 +00:00
|
|
|
|
2010-10-24 08:52:00 +00:00
|
|
|
:param receiver: The callback function which will be connected to this
|
|
|
|
signal. See :ref:`receiver-functions` for more information.
|
2012-06-08 10:00:51 +00:00
|
|
|
|
2010-10-24 08:52:00 +00:00
|
|
|
:param sender: Specifies a particular sender to receive signals from. See
|
|
|
|
:ref:`connecting-to-specific-signals` for more information.
|
|
|
|
|
|
|
|
:param weak: Django stores signal handlers as weak references by
|
|
|
|
default. Thus, if your receiver is a local function, it may be
|
|
|
|
garbage collected. To prevent this, pass ``weak=False`` when you call
|
|
|
|
the signal's ``connect()`` method.
|
|
|
|
|
|
|
|
:param dispatch_uid: A unique identifier for a signal receiver in cases
|
|
|
|
where duplicate signals may be sent. See
|
|
|
|
:ref:`preventing-duplicate-signals` for more information.
|
|
|
|
|
|
|
|
Let's see how this works by registering a signal that
|
2008-08-26 19:04:52 +00:00
|
|
|
gets called after each HTTP request is finished. We'll be connecting to the
|
|
|
|
:data:`~django.core.signals.request_finished` signal.
|
|
|
|
|
2010-10-24 08:52:00 +00:00
|
|
|
.. _receiver-functions:
|
|
|
|
|
2008-08-26 19:04:52 +00:00
|
|
|
Receiver functions
|
|
|
|
------------------
|
|
|
|
|
2010-10-24 08:52:00 +00:00
|
|
|
First, we need to define a receiver function. A receiver can be any Python
|
2014-08-18 14:30:44 +00:00
|
|
|
function or method::
|
2008-08-26 19:04:52 +00:00
|
|
|
|
|
|
|
def my_callback(sender, **kwargs):
|
2012-04-28 16:02:01 +00:00
|
|
|
print("Request finished!")
|
2008-08-26 19:04:52 +00:00
|
|
|
|
|
|
|
Notice that the function takes a ``sender`` argument, along with wildcard
|
|
|
|
keyword arguments (``**kwargs``); all signal handlers must take these arguments.
|
|
|
|
|
2021-11-04 09:46:01 +00:00
|
|
|
We'll look at senders :ref:`a bit later <connecting-to-specific-signals>`, but
|
|
|
|
right now look at the ``**kwargs`` argument. All signals send keyword
|
|
|
|
arguments, and may change those keyword arguments at any time. In the case of
|
2008-08-26 19:04:52 +00:00
|
|
|
:data:`~django.core.signals.request_finished`, it's documented as sending no
|
|
|
|
arguments, which means we might be tempted to write our signal handling as
|
|
|
|
``my_callback(sender)``.
|
|
|
|
|
|
|
|
This would be wrong -- in fact, Django will throw an error if you do so. That's
|
|
|
|
because at any point arguments could get added to the signal and your receiver
|
|
|
|
must be able to handle those new arguments.
|
|
|
|
|
2020-11-07 10:19:20 +00:00
|
|
|
Receivers may also be asynchronous functions, with the same signature but
|
|
|
|
declared using ``async def``::
|
|
|
|
|
|
|
|
async def my_callback(sender, **kwargs):
|
|
|
|
await asyncio.sleep(5)
|
|
|
|
print("Request finished!")
|
|
|
|
|
|
|
|
Signals can be sent either synchronously or asynchronously, and receivers will
|
|
|
|
automatically be adapted to the correct call-style. See :ref:`sending signals
|
|
|
|
<sending-signals>` for more information.
|
|
|
|
|
|
|
|
.. versionchanged:: 5.0
|
|
|
|
|
|
|
|
Support for asynchronous receivers was added.
|
|
|
|
|
2010-10-24 08:52:00 +00:00
|
|
|
.. _connecting-receiver-functions:
|
|
|
|
|
2008-08-26 19:04:52 +00:00
|
|
|
Connecting receiver functions
|
|
|
|
-----------------------------
|
|
|
|
|
2011-05-13 04:33:42 +00:00
|
|
|
There are two ways you can connect a receiver to a signal. You can take the
|
2014-08-18 14:30:44 +00:00
|
|
|
manual connect route::
|
2008-08-26 19:04:52 +00:00
|
|
|
|
|
|
|
from django.core.signals import request_finished
|
|
|
|
|
|
|
|
request_finished.connect(my_callback)
|
|
|
|
|
2013-12-30 12:24:24 +00:00
|
|
|
Alternatively, you can use a :func:`receiver` decorator:
|
|
|
|
|
2022-08-15 20:46:54 +00:00
|
|
|
.. function:: receiver(signal, **kwargs)
|
2013-12-30 12:24:24 +00:00
|
|
|
|
|
|
|
:param signal: A signal or a list of signals to connect a function to.
|
2022-08-15 20:46:54 +00:00
|
|
|
:param kwargs: Wildcard keyword arguments to pass to a
|
|
|
|
:ref:`function <receiver-functions>`.
|
2013-12-30 12:24:24 +00:00
|
|
|
|
2014-08-18 14:30:44 +00:00
|
|
|
Here's how you connect with the decorator::
|
2010-09-12 19:58:05 +00:00
|
|
|
|
|
|
|
from django.core.signals import request_finished
|
|
|
|
from django.dispatch import receiver
|
|
|
|
|
2023-02-28 19:53:28 +00:00
|
|
|
|
2010-09-12 19:58:05 +00:00
|
|
|
@receiver(request_finished)
|
|
|
|
def my_callback(sender, **kwargs):
|
2012-04-28 16:02:01 +00:00
|
|
|
print("Request finished!")
|
2010-09-12 19:58:05 +00:00
|
|
|
|
2008-08-26 19:04:52 +00:00
|
|
|
Now, our ``my_callback`` function will be called each time a request finishes.
|
|
|
|
|
|
|
|
.. admonition:: Where should this code live?
|
|
|
|
|
2013-12-30 12:24:24 +00:00
|
|
|
Strictly speaking, signal handling and registration code can live anywhere
|
|
|
|
you like, although it's recommended to avoid the application's root module
|
|
|
|
and its ``models`` module to minimize side-effects of importing code.
|
|
|
|
|
|
|
|
In practice, signal handlers are usually defined in a ``signals``
|
|
|
|
submodule of the application they relate to. Signal receivers are
|
2013-12-31 16:55:12 +00:00
|
|
|
connected in the :meth:`~django.apps.AppConfig.ready` method of your
|
2021-10-02 13:46:04 +00:00
|
|
|
application :ref:`configuration class <configuring-applications-ref>`. If
|
|
|
|
you're using the :func:`receiver` decorator, import the ``signals``
|
|
|
|
submodule inside :meth:`~django.apps.AppConfig.ready`, this will implicitly
|
|
|
|
connect signal handlers::
|
|
|
|
|
|
|
|
from django.apps import AppConfig
|
2021-11-26 10:16:35 +00:00
|
|
|
from django.core.signals import request_finished
|
2021-10-02 13:46:04 +00:00
|
|
|
|
2023-02-28 19:53:28 +00:00
|
|
|
|
2021-10-02 13:46:04 +00:00
|
|
|
class MyAppConfig(AppConfig):
|
|
|
|
...
|
|
|
|
|
|
|
|
def ready(self):
|
2022-07-02 14:45:24 +00:00
|
|
|
# Implicitly connect signal handlers decorated with @receiver.
|
2021-10-02 13:46:04 +00:00
|
|
|
from . import signals
|
2023-02-28 19:53:28 +00:00
|
|
|
|
2021-10-02 13:46:04 +00:00
|
|
|
# Explicitly connect a signal handler.
|
2021-11-26 10:16:35 +00:00
|
|
|
request_finished.connect(signals.my_callback)
|
2013-12-30 12:24:24 +00:00
|
|
|
|
2014-11-27 16:22:23 +00:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
The :meth:`~django.apps.AppConfig.ready` method may be executed more than
|
|
|
|
once during testing, so you may want to :ref:`guard your signals from
|
|
|
|
duplication <preventing-duplicate-signals>`, especially if you're planning
|
|
|
|
to send them within tests.
|
|
|
|
|
2010-10-24 08:52:00 +00:00
|
|
|
.. _connecting-to-specific-signals:
|
|
|
|
|
2008-08-26 19:04:52 +00:00
|
|
|
Connecting to signals sent by specific senders
|
|
|
|
----------------------------------------------
|
|
|
|
|
2010-04-05 15:46:44 +00:00
|
|
|
Some signals get sent many times, but you'll only be interested in receiving a
|
2008-08-26 19:04:52 +00:00
|
|
|
certain subset of those signals. For example, consider the
|
|
|
|
:data:`django.db.models.signals.pre_save` signal sent before a model gets saved.
|
|
|
|
Most of the time, you don't need to know when *any* model gets saved -- just
|
|
|
|
when one *specific* model is saved.
|
|
|
|
|
|
|
|
In these cases, you can register to receive signals sent only by particular
|
|
|
|
senders. In the case of :data:`django.db.models.signals.pre_save`, the sender
|
|
|
|
will be the model class being saved, so you can indicate that you only want
|
2014-08-18 14:30:44 +00:00
|
|
|
signals sent by some model::
|
2008-08-26 19:04:52 +00:00
|
|
|
|
|
|
|
from django.db.models.signals import pre_save
|
2010-09-12 19:58:05 +00:00
|
|
|
from django.dispatch import receiver
|
2008-08-26 19:04:52 +00:00
|
|
|
from myapp.models import MyModel
|
|
|
|
|
2014-08-18 14:30:44 +00:00
|
|
|
|
2010-09-12 19:58:05 +00:00
|
|
|
@receiver(pre_save, sender=MyModel)
|
2008-08-26 19:04:52 +00:00
|
|
|
def my_handler(sender, **kwargs): ...
|
|
|
|
|
|
|
|
The ``my_handler`` function will only be called when an instance of ``MyModel``
|
|
|
|
is saved.
|
|
|
|
|
|
|
|
Different signals use different objects as their senders; you'll need to consult
|
2010-08-19 19:27:44 +00:00
|
|
|
the :doc:`built-in signal documentation </ref/signals>` for details of each
|
2008-08-26 19:04:52 +00:00
|
|
|
particular signal.
|
|
|
|
|
2010-10-24 08:52:00 +00:00
|
|
|
.. _preventing-duplicate-signals:
|
|
|
|
|
|
|
|
Preventing duplicate signals
|
|
|
|
----------------------------
|
|
|
|
|
2013-12-30 12:24:24 +00:00
|
|
|
In some circumstances, the code connecting receivers to signals may run
|
|
|
|
multiple times. This can cause your receiver function to be registered more
|
2020-07-01 02:54:39 +00:00
|
|
|
than once, and thus called as many times for a signal event. For example, the
|
|
|
|
:meth:`~django.apps.AppConfig.ready` method may be executed more than once
|
|
|
|
during testing. More generally, this occurs everywhere your project imports the
|
|
|
|
module where you define the signals, because signal registration runs as many
|
|
|
|
times as it is imported.
|
2010-10-24 08:52:00 +00:00
|
|
|
|
|
|
|
If this behavior is problematic (such as when using signals to
|
2011-04-01 16:10:22 +00:00
|
|
|
send an email whenever a model is saved), pass a unique identifier as
|
2010-10-24 08:52:00 +00:00
|
|
|
the ``dispatch_uid`` argument to identify your receiver function. This
|
|
|
|
identifier will usually be a string, although any hashable object will
|
|
|
|
suffice. The end result is that your receiver function will only be
|
2014-08-18 14:30:44 +00:00
|
|
|
bound to the signal once for each unique ``dispatch_uid`` value::
|
2010-10-24 08:52:00 +00:00
|
|
|
|
|
|
|
from django.core.signals import request_finished
|
|
|
|
|
|
|
|
request_finished.connect(my_callback, dispatch_uid="my_unique_identifier")
|
|
|
|
|
2022-10-22 16:52:53 +00:00
|
|
|
.. _defining-and-sending-signals:
|
|
|
|
|
2008-08-26 19:04:52 +00:00
|
|
|
Defining and sending signals
|
|
|
|
============================
|
|
|
|
|
2010-10-24 08:52:00 +00:00
|
|
|
Your applications can take advantage of the signal infrastructure and provide
|
|
|
|
its own signals.
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2019-09-25 09:28:08 +00:00
|
|
|
.. admonition:: When to use custom signals
|
|
|
|
|
|
|
|
Signals are implicit function calls which make debugging harder. If the
|
|
|
|
sender and receiver of your custom signal are both within your project,
|
|
|
|
you're better off using an explicit function call.
|
|
|
|
|
2008-08-26 19:04:52 +00:00
|
|
|
Defining signals
|
|
|
|
----------------
|
|
|
|
|
2020-03-01 17:22:03 +00:00
|
|
|
.. class:: Signal()
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2020-03-01 17:22:03 +00:00
|
|
|
All signals are :class:`django.dispatch.Signal` instances.
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2014-08-18 14:30:44 +00:00
|
|
|
For example::
|
2008-08-26 19:04:52 +00:00
|
|
|
|
|
|
|
import django.dispatch
|
|
|
|
|
2020-03-01 17:22:03 +00:00
|
|
|
pizza_done = django.dispatch.Signal()
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2020-03-01 17:22:03 +00:00
|
|
|
This declares a ``pizza_done`` signal.
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2020-11-07 10:19:20 +00:00
|
|
|
.. _sending-signals:
|
|
|
|
|
2008-08-26 19:04:52 +00:00
|
|
|
Sending signals
|
|
|
|
---------------
|
|
|
|
|
2020-11-07 10:19:20 +00:00
|
|
|
There are two ways to send signals synchronously in Django.
|
2010-10-24 08:52:00 +00:00
|
|
|
|
2008-08-26 19:04:52 +00:00
|
|
|
.. method:: Signal.send(sender, **kwargs)
|
2010-10-24 08:52:00 +00:00
|
|
|
.. method:: Signal.send_robust(sender, **kwargs)
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2020-11-07 10:19:20 +00:00
|
|
|
Signals may also be sent asynchronously.
|
|
|
|
|
|
|
|
.. method:: Signal.asend(sender, **kwargs)
|
|
|
|
.. method:: Signal.asend_robust(sender, **kwargs)
|
|
|
|
|
|
|
|
To send a signal, call either :meth:`Signal.send`, :meth:`Signal.send_robust`,
|
|
|
|
:meth:`await Signal.asend()<Signal.asend>`, or
|
|
|
|
:meth:`await Signal.asend_robust() <Signal.asend_robust>`. You must provide the
|
|
|
|
``sender`` argument (which is a class most of the time) and may provide as many
|
|
|
|
other keyword arguments as you like.
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2014-08-18 14:30:44 +00:00
|
|
|
For example, here's how sending our ``pizza_done`` signal might look::
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2017-06-26 14:30:31 +00:00
|
|
|
class PizzaStore:
|
2008-08-26 19:04:52 +00:00
|
|
|
...
|
|
|
|
|
|
|
|
def send_pizza(self, toppings, size):
|
2014-04-25 21:13:58 +00:00
|
|
|
pizza_done.send(sender=self.__class__, toppings=toppings, size=size)
|
2008-08-26 19:04:52 +00:00
|
|
|
...
|
|
|
|
|
2020-11-07 10:19:20 +00:00
|
|
|
All four methods return a list of tuple pairs ``[(receiver, response), ...]``,
|
|
|
|
representing the list of called receiver functions and their response values.
|
2010-10-24 08:52:00 +00:00
|
|
|
|
|
|
|
``send()`` differs from ``send_robust()`` in how exceptions raised by receiver
|
|
|
|
functions are handled. ``send()`` does *not* catch any exceptions raised by
|
|
|
|
receivers; it simply allows errors to propagate. Thus not all receivers may
|
|
|
|
be notified of a signal in the face of an error.
|
|
|
|
|
|
|
|
``send_robust()`` catches all errors derived from Python's ``Exception`` class,
|
|
|
|
and ensures all receivers are notified of the signal. If an error occurs, the
|
|
|
|
error instance is returned in the tuple pair for the receiver that raised the error.
|
|
|
|
|
2015-09-12 20:27:30 +00:00
|
|
|
The tracebacks are present on the ``__traceback__`` attribute of the errors
|
|
|
|
returned when calling ``send_robust()``.
|
2013-10-30 11:11:04 +00:00
|
|
|
|
2020-11-07 10:19:20 +00:00
|
|
|
``asend()`` is similar as ``send()``, but it is coroutine that must be
|
|
|
|
awaited::
|
|
|
|
|
|
|
|
async def asend_pizza(self, toppings, size):
|
|
|
|
await pizza_done.asend(sender=self.__class__, toppings=toppings, size=size)
|
|
|
|
...
|
|
|
|
|
|
|
|
Whether synchronous or asynchronous, receivers will be correctly adapted to
|
|
|
|
whether ``send()`` or ``asend()`` is used. Synchronous receivers will be
|
|
|
|
called using :func:`~.sync_to_async` when invoked via ``asend()``. Asynchronous
|
|
|
|
receivers will be called using :func:`~.async_to_sync` when invoked via
|
|
|
|
``sync()``. Similar to the :ref:`case for middleware <async_performance>`,
|
|
|
|
there is a small performance cost to adapting receivers in this way. Note that
|
|
|
|
in order to reduce the number of sync/async calling-style switches within a
|
|
|
|
``send()`` or ``asend()`` call, the receivers are grouped by whether or not
|
|
|
|
they are async before being called. This means that an asynchronous receiver
|
|
|
|
registered before a synchronous receiver may be executed after the synchronous
|
|
|
|
receiver. In addition, async receivers are executed concurrently using
|
|
|
|
``asyncio.gather()``.
|
|
|
|
|
|
|
|
All built-in signals, except those in the async request-response cycle, are
|
|
|
|
dispatched using :meth:`Signal.send`.
|
|
|
|
|
|
|
|
.. versionchanged:: 5.0
|
|
|
|
|
|
|
|
Support for asynchronous signals was added.
|
|
|
|
|
2010-10-24 08:52:00 +00:00
|
|
|
Disconnecting signals
|
|
|
|
=====================
|
|
|
|
|
2015-07-27 12:35:21 +00:00
|
|
|
.. method:: Signal.disconnect(receiver=None, sender=None, dispatch_uid=None)
|
2010-10-24 08:52:00 +00:00
|
|
|
|
|
|
|
To disconnect a receiver from a signal, call :meth:`Signal.disconnect`. The
|
2015-01-02 14:25:33 +00:00
|
|
|
arguments are as described in :meth:`.Signal.connect`. The method returns
|
2021-04-02 11:59:15 +00:00
|
|
|
``True`` if a receiver was disconnected and ``False`` if not. When ``sender``
|
|
|
|
is passed as a lazy reference to ``<app label>.<model>``, this method always
|
|
|
|
returns ``None``.
|
2008-08-26 19:04:52 +00:00
|
|
|
|
2015-01-02 14:25:33 +00:00
|
|
|
The ``receiver`` argument indicates the registered receiver to disconnect. It
|
|
|
|
may be ``None`` if ``dispatch_uid`` is used to identify the receiver.
|