1. =======
    
  2. Signals
    
  3. =======
    
  4. 
    
  5. .. module:: django.dispatch
    
  6.    :synopsis: Signal dispatch
    
  7. 
    
  8. Django includes a "signal dispatcher" which helps decoupled applications get
    
  9. notified when actions occur elsewhere in the framework. In a nutshell, signals
    
  10. allow certain *senders* to notify a set of *receivers* that some action has
    
  11. taken place. They're especially useful when many pieces of code may be
    
  12. interested in the same events.
    
  13. 
    
  14. For example, a third-party app can register to be notified of settings
    
  15. changes::
    
  16. 
    
  17.     from django.apps import AppConfig
    
  18.     from django.core.signals import setting_changed
    
  19. 
    
  20.     def my_callback(sender, **kwargs):
    
  21.         print("Setting changed!")
    
  22. 
    
  23.     class MyAppConfig(AppConfig):
    
  24.         ...
    
  25. 
    
  26.         def ready(self):
    
  27.             setting_changed.connect(my_callback)
    
  28. 
    
  29. Django's :doc:`built-in signals </ref/signals>` let user code get notified of
    
  30. certain actions.
    
  31. 
    
  32. You can also define and send your own custom signals. See
    
  33. :ref:`defining-and-sending-signals` below.
    
  34. 
    
  35. .. warning::
    
  36. 
    
  37.     Signals give the appearance of loose coupling, but they can quickly lead to
    
  38.     code that is hard to understand, adjust and debug.
    
  39. 
    
  40.     Where possible you should opt for directly calling the handling code,
    
  41.     rather than dispatching via a signal.
    
  42. 
    
  43. Listening to signals
    
  44. ====================
    
  45. 
    
  46. To receive a signal, register a *receiver* function using the
    
  47. :meth:`Signal.connect` method. The receiver function is called when the signal
    
  48. is sent. All of the signal's receiver functions are called one at a time, in
    
  49. the order they were registered.
    
  50. 
    
  51. .. method:: Signal.connect(receiver, sender=None, weak=True, dispatch_uid=None)
    
  52. 
    
  53.     :param receiver: The callback function which will be connected to this
    
  54.         signal. See :ref:`receiver-functions` for more information.
    
  55. 
    
  56.     :param sender: Specifies a particular sender to receive signals from. See
    
  57.         :ref:`connecting-to-specific-signals` for more information.
    
  58. 
    
  59.     :param weak: Django stores signal handlers as weak references by
    
  60.         default. Thus, if your receiver is a local function, it may be
    
  61.         garbage collected. To prevent this, pass ``weak=False`` when you call
    
  62.         the signal's ``connect()`` method.
    
  63. 
    
  64.     :param dispatch_uid: A unique identifier for a signal receiver in cases
    
  65.         where duplicate signals may be sent. See
    
  66.         :ref:`preventing-duplicate-signals` for more information.
    
  67. 
    
  68. Let's see how this works by registering a signal that
    
  69. gets called after each HTTP request is finished. We'll be connecting to the
    
  70. :data:`~django.core.signals.request_finished` signal.
    
  71. 
    
  72. .. _receiver-functions:
    
  73. 
    
  74. Receiver functions
    
  75. ------------------
    
  76. 
    
  77. First, we need to define a receiver function. A receiver can be any Python
    
  78. function or method::
    
  79. 
    
  80.     def my_callback(sender, **kwargs):
    
  81.         print("Request finished!")
    
  82. 
    
  83. Notice that the function takes a ``sender`` argument, along with wildcard
    
  84. keyword arguments (``**kwargs``); all signal handlers must take these arguments.
    
  85. 
    
  86. We'll look at senders :ref:`a bit later <connecting-to-specific-signals>`, but
    
  87. right now look at the ``**kwargs`` argument. All signals send keyword
    
  88. arguments, and may change those keyword arguments at any time. In the case of
    
  89. :data:`~django.core.signals.request_finished`, it's documented as sending no
    
  90. arguments, which means we might be tempted to write our signal handling as
    
  91. ``my_callback(sender)``.
    
  92. 
    
  93. This would be wrong -- in fact, Django will throw an error if you do so. That's
    
  94. because at any point arguments could get added to the signal and your receiver
    
  95. must be able to handle those new arguments.
    
  96. 
    
  97. .. _connecting-receiver-functions:
    
  98. 
    
  99. Connecting receiver functions
    
  100. -----------------------------
    
  101. 
    
  102. There are two ways you can connect a receiver to a signal. You can take the
    
  103. manual connect route::
    
  104. 
    
  105.     from django.core.signals import request_finished
    
  106. 
    
  107.     request_finished.connect(my_callback)
    
  108. 
    
  109. Alternatively, you can use a :func:`receiver` decorator:
    
  110. 
    
  111. .. function:: receiver(signal, **kwargs)
    
  112. 
    
  113.     :param signal: A signal or a list of signals to connect a function to.
    
  114.     :param kwargs: Wildcard keyword arguments to pass to a
    
  115.         :ref:`function <receiver-functions>`.
    
  116. 
    
  117. Here's how you connect with the decorator::
    
  118. 
    
  119.     from django.core.signals import request_finished
    
  120.     from django.dispatch import receiver
    
  121. 
    
  122.     @receiver(request_finished)
    
  123.     def my_callback(sender, **kwargs):
    
  124.         print("Request finished!")
    
  125. 
    
  126. Now, our ``my_callback`` function will be called each time a request finishes.
    
  127. 
    
  128. .. admonition:: Where should this code live?
    
  129. 
    
  130.     Strictly speaking, signal handling and registration code can live anywhere
    
  131.     you like, although it's recommended to avoid the application's root module
    
  132.     and its ``models`` module to minimize side-effects of importing code.
    
  133. 
    
  134.     In practice, signal handlers are usually defined in a ``signals``
    
  135.     submodule of the application they relate to. Signal receivers are
    
  136.     connected in the :meth:`~django.apps.AppConfig.ready` method of your
    
  137.     application :ref:`configuration class <configuring-applications-ref>`. If
    
  138.     you're using the :func:`receiver` decorator, import the ``signals``
    
  139.     submodule inside :meth:`~django.apps.AppConfig.ready`, this will implicitly
    
  140.     connect signal handlers::
    
  141. 
    
  142.         from django.apps import AppConfig
    
  143.         from django.core.signals import request_finished
    
  144. 
    
  145.         class MyAppConfig(AppConfig):
    
  146.             ...
    
  147. 
    
  148.             def ready(self):
    
  149.                 # Implicitly connect signal handlers decorated with @receiver.
    
  150.                 from . import signals
    
  151.                 # Explicitly connect a signal handler.
    
  152.                 request_finished.connect(signals.my_callback)
    
  153. 
    
  154. .. note::
    
  155. 
    
  156.     The :meth:`~django.apps.AppConfig.ready` method may be executed more than
    
  157.     once during testing, so you may want to :ref:`guard your signals from
    
  158.     duplication <preventing-duplicate-signals>`, especially if you're planning
    
  159.     to send them within tests.
    
  160. 
    
  161. .. _connecting-to-specific-signals:
    
  162. 
    
  163. Connecting to signals sent by specific senders
    
  164. ----------------------------------------------
    
  165. 
    
  166. Some signals get sent many times, but you'll only be interested in receiving a
    
  167. certain subset of those signals. For example, consider the
    
  168. :data:`django.db.models.signals.pre_save` signal sent before a model gets saved.
    
  169. Most of the time, you don't need to know when *any* model gets saved -- just
    
  170. when one *specific* model is saved.
    
  171. 
    
  172. In these cases, you can register to receive signals sent only by particular
    
  173. senders. In the case of :data:`django.db.models.signals.pre_save`, the sender
    
  174. will be the model class being saved, so you can indicate that you only want
    
  175. signals sent by some model::
    
  176. 
    
  177.     from django.db.models.signals import pre_save
    
  178.     from django.dispatch import receiver
    
  179.     from myapp.models import MyModel
    
  180. 
    
  181. 
    
  182.     @receiver(pre_save, sender=MyModel)
    
  183.     def my_handler(sender, **kwargs):
    
  184.         ...
    
  185. 
    
  186. The ``my_handler`` function will only be called when an instance of ``MyModel``
    
  187. is saved.
    
  188. 
    
  189. Different signals use different objects as their senders; you'll need to consult
    
  190. the :doc:`built-in signal documentation </ref/signals>` for details of each
    
  191. particular signal.
    
  192. 
    
  193. .. _preventing-duplicate-signals:
    
  194. 
    
  195. Preventing duplicate signals
    
  196. ----------------------------
    
  197. 
    
  198. In some circumstances, the code connecting receivers to signals may run
    
  199. multiple times. This can cause your receiver function to be registered more
    
  200. than once, and thus called as many times for a signal event. For example, the
    
  201. :meth:`~django.apps.AppConfig.ready` method may be executed more than once
    
  202. during testing. More generally, this occurs everywhere your project imports the
    
  203. module where you define the signals, because signal registration runs as many
    
  204. times as it is imported.
    
  205. 
    
  206. If this behavior is problematic (such as when using signals to
    
  207. send an email whenever a model is saved), pass a unique identifier as
    
  208. the ``dispatch_uid`` argument to identify your receiver function. This
    
  209. identifier will usually be a string, although any hashable object will
    
  210. suffice. The end result is that your receiver function will only be
    
  211. bound to the signal once for each unique ``dispatch_uid`` value::
    
  212. 
    
  213.     from django.core.signals import request_finished
    
  214. 
    
  215.     request_finished.connect(my_callback, dispatch_uid="my_unique_identifier")
    
  216. 
    
  217. .. _defining-and-sending-signals:
    
  218. 
    
  219. Defining and sending signals
    
  220. ============================
    
  221. 
    
  222. Your applications can take advantage of the signal infrastructure and provide
    
  223. its own signals.
    
  224. 
    
  225. .. admonition:: When to use custom signals
    
  226. 
    
  227.     Signals are implicit function calls which make debugging harder. If the
    
  228.     sender and receiver of your custom signal are both within your project,
    
  229.     you're better off using an explicit function call.
    
  230. 
    
  231. Defining signals
    
  232. ----------------
    
  233. 
    
  234. .. class:: Signal()
    
  235. 
    
  236. All signals are :class:`django.dispatch.Signal` instances.
    
  237. 
    
  238. For example::
    
  239. 
    
  240.     import django.dispatch
    
  241. 
    
  242.     pizza_done = django.dispatch.Signal()
    
  243. 
    
  244. This declares a ``pizza_done`` signal.
    
  245. 
    
  246. Sending signals
    
  247. ---------------
    
  248. 
    
  249. There are two ways to send signals in Django.
    
  250. 
    
  251. .. method:: Signal.send(sender, **kwargs)
    
  252. .. method:: Signal.send_robust(sender, **kwargs)
    
  253. 
    
  254. To send a signal, call either :meth:`Signal.send` (all built-in signals use
    
  255. this) or :meth:`Signal.send_robust`. You must provide the ``sender`` argument
    
  256. (which is a class most of the time) and may provide as many other keyword
    
  257. arguments as you like.
    
  258. 
    
  259. For example, here's how sending our ``pizza_done`` signal might look::
    
  260. 
    
  261.     class PizzaStore:
    
  262.         ...
    
  263. 
    
  264.         def send_pizza(self, toppings, size):
    
  265.             pizza_done.send(sender=self.__class__, toppings=toppings, size=size)
    
  266.             ...
    
  267. 
    
  268. Both ``send()`` and ``send_robust()`` return a list of tuple pairs
    
  269. ``[(receiver, response), ... ]``, representing the list of called receiver
    
  270. functions and their response values.
    
  271. 
    
  272. ``send()`` differs from ``send_robust()`` in how exceptions raised by receiver
    
  273. functions are handled. ``send()`` does *not* catch any exceptions raised by
    
  274. receivers; it simply allows errors to propagate. Thus not all receivers may
    
  275. be notified of a signal in the face of an error.
    
  276. 
    
  277. ``send_robust()`` catches all errors derived from Python's ``Exception`` class,
    
  278. and ensures all receivers are notified of the signal. If an error occurs, the
    
  279. error instance is returned in the tuple pair for the receiver that raised the error.
    
  280. 
    
  281. The tracebacks are present on the ``__traceback__`` attribute of the errors
    
  282. returned when calling ``send_robust()``.
    
  283. 
    
  284. Disconnecting signals
    
  285. =====================
    
  286. 
    
  287. .. method:: Signal.disconnect(receiver=None, sender=None, dispatch_uid=None)
    
  288. 
    
  289. To disconnect a receiver from a signal, call :meth:`Signal.disconnect`. The
    
  290. arguments are as described in :meth:`.Signal.connect`. The method returns
    
  291. ``True`` if a receiver was disconnected and ``False`` if not. When ``sender``
    
  292. is passed as a lazy reference to ``<app label>.<model>``, this method always
    
  293. returns ``None``.
    
  294. 
    
  295. The ``receiver`` argument indicates the registered receiver to disconnect. It
    
  296. may be ``None`` if ``dispatch_uid`` is used to identify the receiver.