signals.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. =======
  2. Signals
  3. =======
  4. .. module:: django.dispatch
  5. :synopsis: Signal dispatch
  6. Django includes a "signal dispatcher" which helps decoupled applications get
  7. notified when actions occur elsewhere in the framework. In a nutshell, signals
  8. allow certain *senders* to notify a set of *receivers* that some action has
  9. taken place. They're especially useful when many pieces of code may be
  10. interested in the same events.
  11. Django provides a :doc:`set of built-in signals </ref/signals>` that let user
  12. code get notified by Django itself of certain actions. These include some useful
  13. notifications:
  14. * :data:`django.db.models.signals.pre_save` &
  15. :data:`django.db.models.signals.post_save`
  16. Sent before or after a model's :meth:`~django.db.models.Model.save` method
  17. is called.
  18. * :data:`django.db.models.signals.pre_delete` &
  19. :data:`django.db.models.signals.post_delete`
  20. Sent before or after a model's :meth:`~django.db.models.Model.delete`
  21. method or queryset's :meth:`~django.db.models.query.QuerySet.delete`
  22. method is called.
  23. * :data:`django.db.models.signals.m2m_changed`
  24. Sent when a :class:`~django.db.models.ManyToManyField` on a model is changed.
  25. * :data:`django.core.signals.request_started` &
  26. :data:`django.core.signals.request_finished`
  27. Sent when Django starts or finishes an HTTP request.
  28. See the :doc:`built-in signal documentation </ref/signals>` for a complete list,
  29. and a complete explanation of each signal.
  30. You can also `define and send your own custom signals`_; see below.
  31. .. _define and send your own custom signals: `defining and sending signals`_
  32. Listening to signals
  33. ====================
  34. To receive a signal, register a *receiver* function using the
  35. :meth:`Signal.connect` method. The receiver function is called when the signal
  36. is sent. All of the signal's receiver functions are called one at a time, in
  37. the order they were registered.
  38. .. method:: Signal.connect(receiver, sender=None, weak=True, dispatch_uid=None)
  39. :param receiver: The callback function which will be connected to this
  40. signal. See :ref:`receiver-functions` for more information.
  41. :param sender: Specifies a particular sender to receive signals from. See
  42. :ref:`connecting-to-specific-signals` for more information.
  43. :param weak: Django stores signal handlers as weak references by
  44. default. Thus, if your receiver is a local function, it may be
  45. garbage collected. To prevent this, pass ``weak=False`` when you call
  46. the signal's ``connect()`` method.
  47. :param dispatch_uid: A unique identifier for a signal receiver in cases
  48. where duplicate signals may be sent. See
  49. :ref:`preventing-duplicate-signals` for more information.
  50. Let's see how this works by registering a signal that
  51. gets called after each HTTP request is finished. We'll be connecting to the
  52. :data:`~django.core.signals.request_finished` signal.
  53. .. _receiver-functions:
  54. Receiver functions
  55. ------------------
  56. First, we need to define a receiver function. A receiver can be any Python
  57. function or method::
  58. def my_callback(sender, **kwargs):
  59. print("Request finished!")
  60. Notice that the function takes a ``sender`` argument, along with wildcard
  61. keyword arguments (``**kwargs``); all signal handlers must take these arguments.
  62. We'll look at senders :ref:`a bit later <connecting-to-specific-signals>`, but
  63. right now look at the ``**kwargs`` argument. All signals send keyword
  64. arguments, and may change those keyword arguments at any time. In the case of
  65. :data:`~django.core.signals.request_finished`, it's documented as sending no
  66. arguments, which means we might be tempted to write our signal handling as
  67. ``my_callback(sender)``.
  68. This would be wrong -- in fact, Django will throw an error if you do so. That's
  69. because at any point arguments could get added to the signal and your receiver
  70. must be able to handle those new arguments.
  71. .. _connecting-receiver-functions:
  72. Connecting receiver functions
  73. -----------------------------
  74. There are two ways you can connect a receiver to a signal. You can take the
  75. manual connect route::
  76. from django.core.signals import request_finished
  77. request_finished.connect(my_callback)
  78. Alternatively, you can use a :func:`receiver` decorator:
  79. .. function:: receiver(signal)
  80. :param signal: A signal or a list of signals to connect a function to.
  81. Here's how you connect with the decorator::
  82. from django.core.signals import request_finished
  83. from django.dispatch import receiver
  84. @receiver(request_finished)
  85. def my_callback(sender, **kwargs):
  86. print("Request finished!")
  87. Now, our ``my_callback`` function will be called each time a request finishes.
  88. .. admonition:: Where should this code live?
  89. Strictly speaking, signal handling and registration code can live anywhere
  90. you like, although it's recommended to avoid the application's root module
  91. and its ``models`` module to minimize side-effects of importing code.
  92. In practice, signal handlers are usually defined in a ``signals``
  93. submodule of the application they relate to. Signal receivers are
  94. connected in the :meth:`~django.apps.AppConfig.ready` method of your
  95. application :ref:`configuration class <configuring-applications-ref>`. If
  96. you're using the :func:`receiver` decorator, import the ``signals``
  97. submodule inside :meth:`~django.apps.AppConfig.ready`, this will implicitly
  98. connect signal handlers::
  99. from django.apps import AppConfig
  100. class MyAppConfig(AppConfig):
  101. ...
  102. def ready(self):
  103. # Implicitly connect a signal handlers decorated with @receiver.
  104. from . import signals
  105. # Explicitly connect a signal handler.
  106. signals.request_finished.connect(signals.my_callback)
  107. .. note::
  108. The :meth:`~django.apps.AppConfig.ready` method may be executed more than
  109. once during testing, so you may want to :ref:`guard your signals from
  110. duplication <preventing-duplicate-signals>`, especially if you're planning
  111. to send them within tests.
  112. .. _connecting-to-specific-signals:
  113. Connecting to signals sent by specific senders
  114. ----------------------------------------------
  115. Some signals get sent many times, but you'll only be interested in receiving a
  116. certain subset of those signals. For example, consider the
  117. :data:`django.db.models.signals.pre_save` signal sent before a model gets saved.
  118. Most of the time, you don't need to know when *any* model gets saved -- just
  119. when one *specific* model is saved.
  120. In these cases, you can register to receive signals sent only by particular
  121. senders. In the case of :data:`django.db.models.signals.pre_save`, the sender
  122. will be the model class being saved, so you can indicate that you only want
  123. signals sent by some model::
  124. from django.db.models.signals import pre_save
  125. from django.dispatch import receiver
  126. from myapp.models import MyModel
  127. @receiver(pre_save, sender=MyModel)
  128. def my_handler(sender, **kwargs):
  129. ...
  130. The ``my_handler`` function will only be called when an instance of ``MyModel``
  131. is saved.
  132. Different signals use different objects as their senders; you'll need to consult
  133. the :doc:`built-in signal documentation </ref/signals>` for details of each
  134. particular signal.
  135. .. _preventing-duplicate-signals:
  136. Preventing duplicate signals
  137. ----------------------------
  138. In some circumstances, the code connecting receivers to signals may run
  139. multiple times. This can cause your receiver function to be registered more
  140. than once, and thus called as many times for a signal event. For example, the
  141. :meth:`~django.apps.AppConfig.ready` method may be executed more than once
  142. during testing. More generally, this occurs everywhere your project imports the
  143. module where you define the signals, because signal registration runs as many
  144. times as it is imported.
  145. If this behavior is problematic (such as when using signals to
  146. send an email whenever a model is saved), pass a unique identifier as
  147. the ``dispatch_uid`` argument to identify your receiver function. This
  148. identifier will usually be a string, although any hashable object will
  149. suffice. The end result is that your receiver function will only be
  150. bound to the signal once for each unique ``dispatch_uid`` value::
  151. from django.core.signals import request_finished
  152. request_finished.connect(my_callback, dispatch_uid="my_unique_identifier")
  153. Defining and sending signals
  154. ============================
  155. Your applications can take advantage of the signal infrastructure and provide
  156. its own signals.
  157. .. admonition:: When to use custom signals
  158. Signals are implicit function calls which make debugging harder. If the
  159. sender and receiver of your custom signal are both within your project,
  160. you're better off using an explicit function call.
  161. Defining signals
  162. ----------------
  163. .. class:: Signal()
  164. All signals are :class:`django.dispatch.Signal` instances.
  165. For example::
  166. import django.dispatch
  167. pizza_done = django.dispatch.Signal()
  168. This declares a ``pizza_done`` signal.
  169. Sending signals
  170. ---------------
  171. There are two ways to send signals in Django.
  172. .. method:: Signal.send(sender, **kwargs)
  173. .. method:: Signal.send_robust(sender, **kwargs)
  174. To send a signal, call either :meth:`Signal.send` (all built-in signals use
  175. this) or :meth:`Signal.send_robust`. You must provide the ``sender`` argument
  176. (which is a class most of the time) and may provide as many other keyword
  177. arguments as you like.
  178. For example, here's how sending our ``pizza_done`` signal might look::
  179. class PizzaStore:
  180. ...
  181. def send_pizza(self, toppings, size):
  182. pizza_done.send(sender=self.__class__, toppings=toppings, size=size)
  183. ...
  184. Both ``send()`` and ``send_robust()`` return a list of tuple pairs
  185. ``[(receiver, response), ... ]``, representing the list of called receiver
  186. functions and their response values.
  187. ``send()`` differs from ``send_robust()`` in how exceptions raised by receiver
  188. functions are handled. ``send()`` does *not* catch any exceptions raised by
  189. receivers; it simply allows errors to propagate. Thus not all receivers may
  190. be notified of a signal in the face of an error.
  191. ``send_robust()`` catches all errors derived from Python's ``Exception`` class,
  192. and ensures all receivers are notified of the signal. If an error occurs, the
  193. error instance is returned in the tuple pair for the receiver that raised the error.
  194. The tracebacks are present on the ``__traceback__`` attribute of the errors
  195. returned when calling ``send_robust()``.
  196. Disconnecting signals
  197. =====================
  198. .. method:: Signal.disconnect(receiver=None, sender=None, dispatch_uid=None)
  199. To disconnect a receiver from a signal, call :meth:`Signal.disconnect`. The
  200. arguments are as described in :meth:`.Signal.connect`. The method returns
  201. ``True`` if a receiver was disconnected and ``False`` if not. When ``sender``
  202. is passed as a lazy reference to ``<app label>.<model>``, this method always
  203. returns ``None``.
  204. The ``receiver`` argument indicates the registered receiver to disconnect. It
  205. may be ``None`` if ``dispatch_uid`` is used to identify the receiver.