signals.txt 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 decorator used when you define your receiver:
  63. .. code-block:: python
  64. from django.core.signals import request_finished
  65. from django.dispatch import receiver
  66. @receiver(request_finished)
  67. def my_callback(sender, **kwargs):
  68. print "Request finished!"
  69. Now, our ``my_callback`` function will be called each time a request finishes.
  70. .. admonition:: Where should this code live?
  71. You can put signal handling and registration code anywhere you like.
  72. However, you'll need to make sure that the module it's in gets imported
  73. early on so that the signal handling gets registered before any signals need
  74. to be sent. This makes your app's ``models.py`` a good place to put
  75. registration of signal handlers.
  76. Connecting to signals sent by specific senders
  77. ----------------------------------------------
  78. Some signals get sent many times, but you'll only be interested in receiving a
  79. certain subset of those signals. For example, consider the
  80. :data:`django.db.models.signals.pre_save` signal sent before a model gets saved.
  81. Most of the time, you don't need to know when *any* model gets saved -- just
  82. when one *specific* model is saved.
  83. In these cases, you can register to receive signals sent only by particular
  84. senders. In the case of :data:`django.db.models.signals.pre_save`, the sender
  85. will be the model class being saved, so you can indicate that you only want
  86. signals sent by some model:
  87. .. code-block:: python
  88. from django.db.models.signals import pre_save
  89. from django.dispatch import receiver
  90. from myapp.models import MyModel
  91. @receiver(pre_save, sender=MyModel)
  92. def my_handler(sender, **kwargs):
  93. ...
  94. The ``my_handler`` function will only be called when an instance of ``MyModel``
  95. is saved.
  96. Different signals use different objects as their senders; you'll need to consult
  97. the :doc:`built-in signal documentation </ref/signals>` for details of each
  98. particular signal.
  99. Defining and sending signals
  100. ============================
  101. Your applications can take advantage of the signal infrastructure and provide its own signals.
  102. Defining signals
  103. ----------------
  104. .. class:: Signal([providing_args=list])
  105. All signals are :class:`django.dispatch.Signal` instances. The
  106. ``providing_args`` is a list of the names of arguments the signal will provide
  107. to listeners.
  108. For example:
  109. .. code-block:: python
  110. import django.dispatch
  111. pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])
  112. This declares a ``pizza_done`` signal that will provide receivers with
  113. ``toppings`` and ``size`` arguments.
  114. 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.
  115. Sending signals
  116. ---------------
  117. .. method:: Signal.send(sender, **kwargs)
  118. 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.
  119. For example, here's how sending our ``pizza_done`` signal might look:
  120. .. code-block:: python
  121. class PizzaStore(object):
  122. ...
  123. def send_pizza(self, toppings, size):
  124. pizza_done.send(sender=self, toppings=toppings, size=size)
  125. ...