PageRenderTime 166ms CodeModel.GetById 4ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/topics/signals.txt

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