signals.txt 13 KB

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