signals.txt 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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 is called.
  22. * :data:`django.db.models.signals.m2m_changed`
  23. Sent when a :class:`ManyToManyField` on a model is changed.
  24. * :data:`django.core.signals.request_started` &
  25. :data:`django.core.signals.request_finished`
  26. Sent when Django starts or finishes an HTTP request.
  27. See the :doc:`built-in signal documentation </ref/signals>` for a complete list,
  28. and a complete explanation of each signal.
  29. You can also `define and send your own custom signals`_; see below.
  30. .. _define and send your own custom signals: `defining and sending signals`_
  31. Listening to signals
  32. ====================
  33. To receive a signal, you need to register a *receiver* function that gets called
  34. when the signal is sent. Let's see how this works by registering a signal that
  35. gets called after each HTTP request is finished. We'll be connecting to the
  36. :data:`~django.core.signals.request_finished` signal.
  37. Receiver functions
  38. ------------------
  39. First, we need to define a receiver function. A receiver can be any Python function or method:
  40. .. code-block:: python
  41. def my_callback(sender, **kwargs):
  42. print "Request finished!"
  43. Notice that the function takes a ``sender`` argument, along with wildcard
  44. keyword arguments (``**kwargs``); all signal handlers must take these arguments.
  45. We'll look at senders `a bit later`_, but right now look at the ``**kwargs``
  46. argument. All signals send keyword arguments, and may change those keyword
  47. arguments at any time. In the case of
  48. :data:`~django.core.signals.request_finished`, it's documented as sending no
  49. arguments, which means we might be tempted to write our signal handling as
  50. ``my_callback(sender)``.
  51. .. _a bit later: `connecting to signals sent by specific senders`_
  52. This would be wrong -- in fact, Django will throw an error if you do so. That's
  53. because at any point arguments could get added to the signal and your receiver
  54. must be able to handle those new arguments.
  55. Connecting receiver functions
  56. -----------------------------
  57. There are two ways you can connect a receiever to a signal. You can take the
  58. manual connect route:
  59. .. code-block:: python
  60. from django.core.signals import request_finished
  61. request_finished.connect(my_callback)
  62. Alternatively, you can use a ``receiver`` decorator when you define your
  63. receiver:
  64. .. code-block:: python
  65. from django.core.signals import request_finished
  66. from django.dispatch import receiver
  67. @receiver(request_finished)
  68. def my_callback(sender, **kwargs):
  69. print "Request finished!"
  70. Now, our ``my_callback`` function will be called each time a request finishes.
  71. .. versionadded:: 1.3
  72. The ``receiver`` decorator was added in Django 1.3.
  73. .. admonition:: Where should this code live?
  74. You can put signal handling and registration code anywhere you like.
  75. However, you'll need to make sure that the module it's in gets imported
  76. early on so that the signal handling gets registered before any signals need
  77. to be sent. This makes your app's ``models.py`` a good place to put
  78. registration of signal handlers.
  79. Connecting to signals sent by specific senders
  80. ----------------------------------------------
  81. Some signals get sent many times, but you'll only be interested in receiving a
  82. certain subset of those signals. For example, consider the
  83. :data:`django.db.models.signals.pre_save` signal sent before a model gets saved.
  84. Most of the time, you don't need to know when *any* model gets saved -- just
  85. when one *specific* model is saved.
  86. In these cases, you can register to receive signals sent only by particular
  87. senders. In the case of :data:`django.db.models.signals.pre_save`, the sender
  88. will be the model class being saved, so you can indicate that you only want
  89. signals sent by some model:
  90. .. code-block:: python
  91. from django.db.models.signals import pre_save
  92. from django.dispatch import receiver
  93. from myapp.models import MyModel
  94. @receiver(pre_save, sender=MyModel)
  95. def my_handler(sender, **kwargs):
  96. ...
  97. The ``my_handler`` function will only be called when an instance of ``MyModel``
  98. is saved.
  99. Different signals use different objects as their senders; you'll need to consult
  100. the :doc:`built-in signal documentation </ref/signals>` for details of each
  101. particular signal.
  102. Defining and sending signals
  103. ============================
  104. Your applications can take advantage of the signal infrastructure and provide its own signals.
  105. Defining signals
  106. ----------------
  107. .. class:: Signal([providing_args=list])
  108. All signals are :class:`django.dispatch.Signal` instances. The
  109. ``providing_args`` is a list of the names of arguments the signal will provide
  110. to listeners.
  111. For example:
  112. .. code-block:: python
  113. import django.dispatch
  114. pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])
  115. This declares a ``pizza_done`` signal that will provide receivers with
  116. ``toppings`` and ``size`` arguments.
  117. 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.
  118. Sending signals
  119. ---------------
  120. .. method:: Signal.send(sender, **kwargs)
  121. To send a signal, call :meth:`Signal.send`. You must provide the ``sender`` argument, and may provide as many other keyword arguments as you like.
  122. For example, here's how sending our ``pizza_done`` signal might look:
  123. .. code-block:: python
  124. class PizzaStore(object):
  125. ...
  126. def send_pizza(self, toppings, size):
  127. pizza_done.send(sender=self, toppings=toppings, size=size)
  128. ...