You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dispatcher.py 11 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. import sys
  2. import threading
  3. import warnings
  4. import weakref
  5. from django.utils import six
  6. from django.utils.deprecation import RemovedInDjango20Warning
  7. from django.utils.inspect import func_accepts_kwargs
  8. from django.utils.six.moves import range
  9. if six.PY2:
  10. from .weakref_backports import WeakMethod
  11. else:
  12. from weakref import WeakMethod
  13. def _make_id(target):
  14. if hasattr(target, '__func__'):
  15. return (id(target.__self__), id(target.__func__))
  16. return id(target)
  17. NONE_ID = _make_id(None)
  18. # A marker for caching
  19. NO_RECEIVERS = object()
  20. class Signal(object):
  21. """
  22. Base class for all signals
  23. Internal attributes:
  24. receivers
  25. { receiverkey (id) : weakref(receiver) }
  26. """
  27. def __init__(self, providing_args=None, use_caching=False):
  28. """
  29. Create a new signal.
  30. providing_args
  31. A list of the arguments this signal can pass along in a send() call.
  32. """
  33. self.receivers = []
  34. if providing_args is None:
  35. providing_args = []
  36. self.providing_args = set(providing_args)
  37. self.lock = threading.Lock()
  38. self.use_caching = use_caching
  39. # For convenience we create empty caches even if they are not used.
  40. # A note about caching: if use_caching is defined, then for each
  41. # distinct sender we cache the receivers that sender has in
  42. # 'sender_receivers_cache'. The cache is cleaned when .connect() or
  43. # .disconnect() is called and populated on send().
  44. self.sender_receivers_cache = weakref.WeakKeyDictionary() if use_caching else {}
  45. self._dead_receivers = False
  46. def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
  47. """
  48. Connect receiver to sender for signal.
  49. Arguments:
  50. receiver
  51. A function or an instance method which is to receive signals.
  52. Receivers must be hashable objects.
  53. If weak is True, then receiver must be weak referenceable.
  54. Receivers must be able to accept keyword arguments.
  55. If a receiver is connected with a dispatch_uid argument, it
  56. will not be added if another receiver was already connected
  57. with that dispatch_uid.
  58. sender
  59. The sender to which the receiver should respond. Must either be
  60. of type Signal, or None to receive events from any sender.
  61. weak
  62. Whether to use weak references to the receiver. By default, the
  63. module will attempt to use weak references to the receiver
  64. objects. If this parameter is false, then strong references will
  65. be used.
  66. dispatch_uid
  67. An identifier used to uniquely identify a particular instance of
  68. a receiver. This will usually be a string, though it may be
  69. anything hashable.
  70. """
  71. from django.conf import settings
  72. # If DEBUG is on, check that we got a good receiver
  73. if settings.configured and settings.DEBUG:
  74. assert callable(receiver), "Signal receivers must be callable."
  75. # Check for **kwargs
  76. if not func_accepts_kwargs(receiver):
  77. raise ValueError("Signal receivers must accept keyword arguments (**kwargs).")
  78. if dispatch_uid:
  79. lookup_key = (dispatch_uid, _make_id(sender))
  80. else:
  81. lookup_key = (_make_id(receiver), _make_id(sender))
  82. if weak:
  83. ref = weakref.ref
  84. receiver_object = receiver
  85. # Check for bound methods
  86. if hasattr(receiver, '__self__') and hasattr(receiver, '__func__'):
  87. ref = WeakMethod
  88. receiver_object = receiver.__self__
  89. if six.PY3:
  90. receiver = ref(receiver)
  91. weakref.finalize(receiver_object, self._remove_receiver)
  92. else:
  93. receiver = ref(receiver, self._remove_receiver)
  94. with self.lock:
  95. self._clear_dead_receivers()
  96. for r_key, _ in self.receivers:
  97. if r_key == lookup_key:
  98. break
  99. else:
  100. self.receivers.append((lookup_key, receiver))
  101. self.sender_receivers_cache.clear()
  102. def disconnect(self, receiver=None, sender=None, weak=None, dispatch_uid=None):
  103. """
  104. Disconnect receiver from sender for signal.
  105. If weak references are used, disconnect need not be called. The receiver
  106. will be remove from dispatch automatically.
  107. Arguments:
  108. receiver
  109. The registered receiver to disconnect. May be none if
  110. dispatch_uid is specified.
  111. sender
  112. The registered sender to disconnect
  113. dispatch_uid
  114. the unique identifier of the receiver to disconnect
  115. """
  116. if weak is not None:
  117. warnings.warn("Passing `weak` to disconnect has no effect.",
  118. RemovedInDjango20Warning, stacklevel=2)
  119. if dispatch_uid:
  120. lookup_key = (dispatch_uid, _make_id(sender))
  121. else:
  122. lookup_key = (_make_id(receiver), _make_id(sender))
  123. disconnected = False
  124. with self.lock:
  125. self._clear_dead_receivers()
  126. for index in range(len(self.receivers)):
  127. (r_key, _) = self.receivers[index]
  128. if r_key == lookup_key:
  129. disconnected = True
  130. del self.receivers[index]
  131. break
  132. self.sender_receivers_cache.clear()
  133. return disconnected
  134. def has_listeners(self, sender=None):
  135. return bool(self._live_receivers(sender))
  136. def send(self, sender, **named):
  137. """
  138. Send signal from sender to all connected receivers.
  139. If any receiver raises an error, the error propagates back through send,
  140. terminating the dispatch loop. So it's possible that all receivers
  141. won't be called if an error is raised.
  142. Arguments:
  143. sender
  144. The sender of the signal. Either a specific object or None.
  145. named
  146. Named arguments which will be passed to receivers.
  147. Returns a list of tuple pairs [(receiver, response), ... ].
  148. """
  149. responses = []
  150. if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
  151. return responses
  152. for receiver in self._live_receivers(sender):
  153. response = receiver(signal=self, sender=sender, **named)
  154. responses.append((receiver, response))
  155. return responses
  156. def send_robust(self, sender, **named):
  157. """
  158. Send signal from sender to all connected receivers catching errors.
  159. Arguments:
  160. sender
  161. The sender of the signal. Can be any python object (normally one
  162. registered with a connect if you actually want something to
  163. occur).
  164. named
  165. Named arguments which will be passed to receivers. These
  166. arguments must be a subset of the argument names defined in
  167. providing_args.
  168. Return a list of tuple pairs [(receiver, response), ... ]. May raise
  169. DispatcherKeyError.
  170. If any receiver raises an error (specifically any subclass of
  171. Exception), the error instance is returned as the result for that
  172. receiver. The traceback is always attached to the error at
  173. ``__traceback__``.
  174. """
  175. responses = []
  176. if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
  177. return responses
  178. # Call each receiver with whatever arguments it can accept.
  179. # Return a list of tuple pairs [(receiver, response), ... ].
  180. for receiver in self._live_receivers(sender):
  181. try:
  182. response = receiver(signal=self, sender=sender, **named)
  183. except Exception as err:
  184. if not hasattr(err, '__traceback__'):
  185. err.__traceback__ = sys.exc_info()[2]
  186. responses.append((receiver, err))
  187. else:
  188. responses.append((receiver, response))
  189. return responses
  190. def _clear_dead_receivers(self):
  191. # Note: caller is assumed to hold self.lock.
  192. if self._dead_receivers:
  193. self._dead_receivers = False
  194. new_receivers = []
  195. for r in self.receivers:
  196. if isinstance(r[1], weakref.ReferenceType) and r[1]() is None:
  197. continue
  198. new_receivers.append(r)
  199. self.receivers = new_receivers
  200. def _live_receivers(self, sender):
  201. """
  202. Filter sequence of receivers to get resolved, live receivers.
  203. This checks for weak references and resolves them, then returning only
  204. live receivers.
  205. """
  206. receivers = None
  207. if self.use_caching and not self._dead_receivers:
  208. receivers = self.sender_receivers_cache.get(sender)
  209. # We could end up here with NO_RECEIVERS even if we do check this case in
  210. # .send() prior to calling _live_receivers() due to concurrent .send() call.
  211. if receivers is NO_RECEIVERS:
  212. return []
  213. if receivers is None:
  214. with self.lock:
  215. self._clear_dead_receivers()
  216. senderkey = _make_id(sender)
  217. receivers = []
  218. for (receiverkey, r_senderkey), receiver in self.receivers:
  219. if r_senderkey == NONE_ID or r_senderkey == senderkey:
  220. receivers.append(receiver)
  221. if self.use_caching:
  222. if not receivers:
  223. self.sender_receivers_cache[sender] = NO_RECEIVERS
  224. else:
  225. # Note, we must cache the weakref versions.
  226. self.sender_receivers_cache[sender] = receivers
  227. non_weak_receivers = []
  228. for receiver in receivers:
  229. if isinstance(receiver, weakref.ReferenceType):
  230. # Dereference the weak reference.
  231. receiver = receiver()
  232. if receiver is not None:
  233. non_weak_receivers.append(receiver)
  234. else:
  235. non_weak_receivers.append(receiver)
  236. return non_weak_receivers
  237. def _remove_receiver(self, receiver=None):
  238. # Mark that the self.receivers list has dead weakrefs. If so, we will
  239. # clean those up in connect, disconnect and _live_receivers while
  240. # holding self.lock. Note that doing the cleanup here isn't a good
  241. # idea, _remove_receiver() will be called as side effect of garbage
  242. # collection, and so the call can happen while we are already holding
  243. # self.lock.
  244. self._dead_receivers = True
  245. def receiver(signal, **kwargs):
  246. """
  247. A decorator for connecting receivers to signals. Used by passing in the
  248. signal (or list of signals) and keyword arguments to connect::
  249. @receiver(post_save, sender=MyModel)
  250. def signal_receiver(sender, **kwargs):
  251. ...
  252. @receiver([post_save, post_delete], sender=MyModel)
  253. def signals_receiver(sender, **kwargs):
  254. ...
  255. """
  256. def _decorator(func):
  257. if isinstance(signal, (list, tuple)):
  258. for s in signal:
  259. s.connect(func, **kwargs)
  260. else:
  261. signal.connect(func, **kwargs)
  262. return func
  263. return _decorator