signals.txt 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. =======
  2. Signals
  3. =======
  4. .. module:: django.dispatch
  5. :synopsis: Signal dispatch
  6. Django includes a "signal dispatcher" which helps allow decoupled applications
  7. get notified when actions occur elsewhere in the framework. In a nutshell,
  8. signals allow certain *senders* to notify a set of *receivers* that some action
  9. has 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, you need to register a *receiver* function that gets
  35. called when the signal is sent by using the
  36. :meth:`.Signal.connect` method:
  37. .. method:: Signal.connect(receiver, [sender=None, weak=True, dispatch_uid=None])
  38. :param receiver: The callback function which will be connected to this
  39. signal. See :ref:`receiver-functions` for more information.
  40. :param sender: Specifies a particular sender to receive signals from. See
  41. :ref:`connecting-to-specific-signals` for more information.
  42. :param weak: Django stores signal handlers as weak references by
  43. default. Thus, if your receiver is a local function, it may be
  44. garbage collected. To prevent this, pass ``weak=False`` when you call
  45. the signal's ``connect()`` method.
  46. :param dispatch_uid: A unique identifier for a signal receiver in cases
  47. where duplicate signals may be sent. See
  48. :ref:`preventing-duplicate-signals` for more information.
  49. Let's see how this works by registering a signal that
  50. gets called after each HTTP request is finished. We'll be connecting to the
  51. :data:`~django.core.signals.request_finished` signal.
  52. .. _receiver-functions:
  53. Receiver functions
  54. ------------------
  55. First, we need to define a receiver function. A receiver can be any Python
  56. function or method:
  57. .. code-block:: python
  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 `a bit later`_, but right now look at the ``**kwargs``
  63. argument. All signals send keyword arguments, and may change those keyword
  64. 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. .. _a bit later: `connecting to signals sent by specific senders`_
  69. This would be wrong -- in fact, Django will throw an error if you do so. That's
  70. because at any point arguments could get added to the signal and your receiver
  71. must be able to handle those new arguments.
  72. .. _connecting-receiver-functions:
  73. Connecting receiver functions
  74. -----------------------------
  75. There are two ways you can connect a receiver to a signal. You can take the
  76. manual connect route:
  77. .. code-block:: python
  78. from django.core.signals import request_finished
  79. request_finished.connect(my_callback)
  80. Alternatively, you can use a ``receiver`` decorator when you define your
  81. receiver:
  82. .. code-block:: python
  83. from django.core.signals import request_finished
  84. from django.dispatch import receiver
  85. @receiver(request_finished)
  86. def my_callback(sender, **kwargs):
  87. print("Request finished!")
  88. Now, our ``my_callback`` function will be called each time a request finishes.
  89. Note that ``receiver`` can also take a list of signals to connect a function
  90. to.
  91. .. versionchanged:: 1.5
  92. The ability to pass a list of signals was added.
  93. .. admonition:: Where should this code live?
  94. You can put signal handling and registration code anywhere you like.
  95. However, you'll need to make sure that the module it's in gets imported
  96. early on so that the signal handling gets registered before any signals need
  97. to be sent. This makes your app's ``models.py`` a good place to put
  98. registration of signal handlers.
  99. .. _connecting-to-specific-signals:
  100. Connecting to signals sent by specific senders
  101. ----------------------------------------------
  102. Some signals get sent many times, but you'll only be interested in receiving a
  103. certain subset of those signals. For example, consider the
  104. :data:`django.db.models.signals.pre_save` signal sent before a model gets saved.
  105. Most of the time, you don't need to know when *any* model gets saved -- just
  106. when one *specific* model is saved.
  107. In these cases, you can register to receive signals sent only by particular
  108. senders. In the case of :data:`django.db.models.signals.pre_save`, the sender
  109. will be the model class being saved, so you can indicate that you only want
  110. signals sent by some model:
  111. .. code-block:: python
  112. from django.db.models.signals import pre_save
  113. from django.dispatch import receiver
  114. from myapp.models import MyModel
  115. @receiver(pre_save, sender=MyModel)
  116. def my_handler(sender, **kwargs):
  117. ...
  118. The ``my_handler`` function will only be called when an instance of ``MyModel``
  119. is saved.
  120. Different signals use different objects as their senders; you'll need to consult
  121. the :doc:`built-in signal documentation </ref/signals>` for details of each
  122. particular signal.
  123. .. _preventing-duplicate-signals:
  124. Preventing duplicate signals
  125. ----------------------------
  126. In some circumstances, the module in which you are connecting signals may be
  127. imported multiple times. This can cause your receiver function to be
  128. registered more than once, and thus called multiples times for a single signal
  129. event.
  130. If this behavior is problematic (such as when using signals to
  131. send an email whenever a model is saved), pass a unique identifier as
  132. the ``dispatch_uid`` argument to identify your receiver function. This
  133. identifier will usually be a string, although any hashable object will
  134. suffice. The end result is that your receiver function will only be
  135. bound to the signal once for each unique ``dispatch_uid`` value.
  136. .. code-block:: python
  137. from django.core.signals import request_finished
  138. request_finished.connect(my_callback, dispatch_uid="my_unique_identifier")
  139. Defining and sending signals
  140. ============================
  141. Your applications can take advantage of the signal infrastructure and provide
  142. its own signals.
  143. Defining signals
  144. ----------------
  145. .. class:: Signal([providing_args=list])
  146. All signals are :class:`django.dispatch.Signal` instances. The
  147. ``providing_args`` is a list of the names of arguments the signal will provide
  148. to listeners. This is purely documentational, however, as there is nothing that
  149. checks that the signal actually provides these arguments to its listeners.
  150. For example:
  151. .. code-block:: python
  152. import django.dispatch
  153. pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])
  154. This declares a ``pizza_done`` signal that will provide receivers with
  155. ``toppings`` and ``size`` arguments.
  156. Remember that you're allowed to change this list of arguments at any time, so getting the API right on the first try isn't necessary.
  157. Sending signals
  158. ---------------
  159. There are two ways to send signals in Django.
  160. .. method:: Signal.send(sender, **kwargs)
  161. .. method:: Signal.send_robust(sender, **kwargs)
  162. To send a signal, call either :meth:`Signal.send` or :meth:`Signal.send_robust`.
  163. You must provide the ``sender`` argument, and may provide as many other keyword
  164. arguments as you like.
  165. For example, here's how sending our ``pizza_done`` signal might look:
  166. .. code-block:: python
  167. class PizzaStore(object):
  168. ...
  169. def send_pizza(self, toppings, size):
  170. pizza_done.send(sender=self, toppings=toppings, size=size)
  171. ...
  172. Both ``send()`` and ``send_robust()`` return a list of tuple pairs
  173. ``[(receiver, response), ... ]``, representing the list of called receiver
  174. functions and their response values.
  175. ``send()`` differs from ``send_robust()`` in how exceptions raised by receiver
  176. functions are handled. ``send()`` does *not* catch any exceptions raised by
  177. receivers; it simply allows errors to propagate. Thus not all receivers may
  178. be notified of a signal in the face of an error.
  179. ``send_robust()`` catches all errors derived from Python's ``Exception`` class,
  180. and ensures all receivers are notified of the signal. If an error occurs, the
  181. error instance is returned in the tuple pair for the receiver that raised the error.
  182. Disconnecting signals
  183. =====================
  184. .. method:: Signal.disconnect([receiver=None, sender=None, weak=True, dispatch_uid=None])
  185. To disconnect a receiver from a signal, call :meth:`Signal.disconnect`. The
  186. arguments are as described in :meth:`.Signal.connect`.
  187. The *receiver* argument indicates the registered receiver to disconnect. It may
  188. be ``None`` if ``dispatch_uid`` is used to identify the receiver.