signals.txt 5.8 KB

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