signals.txt 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. .. _topics-signals:
  2. =======
  3. Signals
  4. =======
  5. .. module:: django.dispatch
  6. :synopsis: Signal dispatch
  7. Django includes a "signal dispatcher" which helps allow decoupled applications
  8. get notified when actions occur elsewhere in the framework. In a nutshell,
  9. signals allow certain *senders* to notify a set of *receivers* that some action
  10. has taken place. They're especially useful when many pieces of code may be
  11. interested in the same events.
  12. Django provides a :ref:`set of built-in signals <ref-signals>` that let user
  13. code get notified by Django itself of certain actions. These include some useful
  14. notifications:
  15. * :data:`django.db.models.signals.pre_save` &
  16. :data:`django.db.models.signals.post_save`
  17. Sent before or after a model's :meth:`~django.db.models.Model.save` method
  18. is called.
  19. * :data:`django.db.models.signals.pre_delete` &
  20. :data:`django.db.models.signals.post_delete`
  21. Sent before or after a model's :meth:`~django.db.models.Model.delete`
  22. method is called.
  23. * :data:`django.db.models.signals.m2m_changed`
  24. Sent when a :class:`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 :ref:`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 called
  35. when the signal is sent. Let's see how this works by registering a signal that
  36. gets called after each HTTP request is finished. We'll be connecting to the
  37. :data:`~django.core.signals.request_finished` signal.
  38. Receiver functions
  39. ------------------
  40. First, we need to define a receiver function. A receiver can be any Python function or method:
  41. .. code-block:: python
  42. def my_callback(sender, **kwargs):
  43. print "Request finished!"
  44. Notice that the function takes a ``sender`` argument, along with wildcard
  45. keyword arguments (``**kwargs``); all signal handlers must take these arguments.
  46. We'll look at senders `a bit later`_, but right now look at the ``**kwargs``
  47. argument. All signals send keyword arguments, and may change those keyword
  48. arguments at any time. In the case of
  49. :data:`~django.core.signals.request_finished`, it's documented as sending no
  50. arguments, which means we might be tempted to write our signal handling as
  51. ``my_callback(sender)``.
  52. .. _a bit later: `connecting to signals sent by specific senders`_
  53. This would be wrong -- in fact, Django will throw an error if you do so. That's
  54. because at any point arguments could get added to the signal and your receiver
  55. must be able to handle those new arguments.
  56. Connecting receiver functions
  57. -----------------------------
  58. Next, we'll need to connect our receiver to the signal:
  59. .. code-block:: python
  60. from django.core.signals import request_finished
  61. request_finished.connect(my_callback)
  62. Now, our ``my_callback`` function will be called each time a request finishes.
  63. .. admonition:: Where should this code live?
  64. You can put signal handling and registration code anywhere you like.
  65. However, you'll need to make sure that the module it's in gets imported
  66. early on so that the signal handling gets registered before any signals need
  67. to be sent. This makes your app's ``models.py`` a good place to put
  68. registration of signal handlers.
  69. Connecting to signals sent by specific senders
  70. ----------------------------------------------
  71. Some signals get sent many times, but you'll only be interested in receiving a
  72. certain subset of those signals. For example, consider the
  73. :data:`django.db.models.signals.pre_save` signal sent before a model gets saved.
  74. Most of the time, you don't need to know when *any* model gets saved -- just
  75. when one *specific* model is saved.
  76. In these cases, you can register to receive signals sent only by particular
  77. senders. In the case of :data:`django.db.models.signals.pre_save`, the sender
  78. will be the model class being saved, so you can indicate that you only want
  79. signals sent by some model:
  80. .. code-block:: python
  81. from django.db.models.signals import pre_save
  82. from myapp.models import MyModel
  83. def my_handler(sender, **kwargs):
  84. ...
  85. pre_save.connect(my_handler, sender=MyModel)
  86. The ``my_handler`` function will only be called when an instance of ``MyModel``
  87. is saved.
  88. Different signals use different objects as their senders; you'll need to consult
  89. the :ref:`built-in signal documentation <ref-signals>` for details of each
  90. particular signal.
  91. Defining and sending signals
  92. ============================
  93. Your applications can take advantage of the signal infrastructure and provide its own signals.
  94. Defining signals
  95. ----------------
  96. .. class:: Signal([providing_args=list])
  97. All signals are :class:`django.dispatch.Signal` instances. The
  98. ``providing_args`` is a list of the names of arguments the signal will provide
  99. to listeners.
  100. For example:
  101. .. code-block:: python
  102. import django.dispatch
  103. pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])
  104. This declares a ``pizza_done`` signal that will provide receivers with
  105. ``toppings`` and ``size`` arguments.
  106. 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.
  107. Sending signals
  108. ---------------
  109. .. method:: Signal.send(sender, **kwargs)
  110. 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.
  111. For example, here's how sending our ``pizza_done`` signal might look:
  112. .. code-block:: python
  113. class PizzaStore(object):
  114. ...
  115. def send_pizza(self, toppings, size):
  116. pizza_done.send(sender=self, toppings=toppings, size=size)
  117. ...