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 10KB

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