Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 11KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import logging
  2. import threading
  3. import weakref
  4. from django.utils.inspect import func_accepts_kwargs
  5. logger = logging.getLogger("django.dispatch")
  6. def _make_id(target):
  7. if hasattr(target, "__func__"):
  8. return (id(target.__self__), id(target.__func__))
  9. return id(target)
  10. NONE_ID = _make_id(None)
  11. # A marker for caching
  12. NO_RECEIVERS = object()
  13. class Signal:
  14. """
  15. Base class for all signals
  16. Internal attributes:
  17. receivers
  18. { receiverkey (id) : weakref(receiver) }
  19. """
  20. def __init__(self, use_caching=False):
  21. """
  22. Create a new signal.
  23. """
  24. self.receivers = []
  25. self.lock = threading.Lock()
  26. self.use_caching = use_caching
  27. # For convenience we create empty caches even if they are not used.
  28. # A note about caching: if use_caching is defined, then for each
  29. # distinct sender we cache the receivers that sender has in
  30. # 'sender_receivers_cache'. The cache is cleaned when .connect() or
  31. # .disconnect() is called and populated on send().
  32. self.sender_receivers_cache = weakref.WeakKeyDictionary() if use_caching else {}
  33. self._dead_receivers = False
  34. def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
  35. """
  36. Connect receiver to sender for signal.
  37. Arguments:
  38. receiver
  39. A function or an instance method which is to receive signals.
  40. Receivers must be hashable objects.
  41. If weak is True, then receiver must be weak referenceable.
  42. Receivers must be able to accept keyword arguments.
  43. If a receiver is connected with a dispatch_uid argument, it
  44. will not be added if another receiver was already connected
  45. with that dispatch_uid.
  46. sender
  47. The sender to which the receiver should respond. Must either be
  48. a Python object, or None to receive events from any sender.
  49. weak
  50. Whether to use weak references to the receiver. By default, the
  51. module will attempt to use weak references to the receiver
  52. objects. If this parameter is false, then strong references will
  53. be used.
  54. dispatch_uid
  55. An identifier used to uniquely identify a particular instance of
  56. a receiver. This will usually be a string, though it may be
  57. anything hashable.
  58. """
  59. from django.conf import settings
  60. # If DEBUG is on, check that we got a good receiver
  61. if settings.configured and settings.DEBUG:
  62. if not callable(receiver):
  63. raise TypeError("Signal receivers must be callable.")
  64. # Check for **kwargs
  65. if not func_accepts_kwargs(receiver):
  66. raise ValueError(
  67. "Signal receivers must accept keyword arguments (**kwargs)."
  68. )
  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 (
  132. not self.receivers
  133. or self.sender_receivers_cache.get(sender) is NO_RECEIVERS
  134. ):
  135. return []
  136. return [
  137. (receiver, receiver(signal=self, sender=sender, **named))
  138. for receiver in self._live_receivers(sender)
  139. ]
  140. def send_robust(self, sender, **named):
  141. """
  142. Send signal from sender to all connected receivers catching errors.
  143. Arguments:
  144. sender
  145. The sender of the signal. Can be any Python object (normally one
  146. registered with a connect if you actually want something to
  147. occur).
  148. named
  149. Named arguments which will be passed to receivers.
  150. Return a list of tuple pairs [(receiver, response), ... ].
  151. If any receiver raises an error (specifically any subclass of
  152. Exception), return the error instance as the result for that receiver.
  153. """
  154. if (
  155. not self.receivers
  156. or self.sender_receivers_cache.get(sender) is NO_RECEIVERS
  157. ):
  158. return []
  159. # Call each receiver with whatever arguments it can accept.
  160. # Return a list of tuple pairs [(receiver, response), ... ].
  161. responses = []
  162. for receiver in self._live_receivers(sender):
  163. try:
  164. response = receiver(signal=self, sender=sender, **named)
  165. except Exception as err:
  166. logger.error(
  167. "Error calling %s in Signal.send_robust() (%s)",
  168. receiver.__qualname__,
  169. err,
  170. exc_info=err,
  171. )
  172. responses.append((receiver, err))
  173. else:
  174. responses.append((receiver, response))
  175. return responses
  176. def _clear_dead_receivers(self):
  177. # Note: caller is assumed to hold self.lock.
  178. if self._dead_receivers:
  179. self._dead_receivers = False
  180. self.receivers = [
  181. r
  182. for r in self.receivers
  183. if not (isinstance(r[1], weakref.ReferenceType) and r[1]() is None)
  184. ]
  185. def _live_receivers(self, sender):
  186. """
  187. Filter sequence of receivers to get resolved, live receivers.
  188. This checks for weak references and resolves them, then returning only
  189. live receivers.
  190. """
  191. receivers = None
  192. if self.use_caching and not self._dead_receivers:
  193. receivers = self.sender_receivers_cache.get(sender)
  194. # We could end up here with NO_RECEIVERS even if we do check this case in
  195. # .send() prior to calling _live_receivers() due to concurrent .send() call.
  196. if receivers is NO_RECEIVERS:
  197. return []
  198. if receivers is None:
  199. with self.lock:
  200. self._clear_dead_receivers()
  201. senderkey = _make_id(sender)
  202. receivers = []
  203. for (receiverkey, r_senderkey), receiver in self.receivers:
  204. if r_senderkey == NONE_ID or r_senderkey == senderkey:
  205. receivers.append(receiver)
  206. if self.use_caching:
  207. if not receivers:
  208. self.sender_receivers_cache[sender] = NO_RECEIVERS
  209. else:
  210. # Note, we must cache the weakref versions.
  211. self.sender_receivers_cache[sender] = receivers
  212. non_weak_receivers = []
  213. for receiver in receivers:
  214. if isinstance(receiver, weakref.ReferenceType):
  215. # Dereference the weak reference.
  216. receiver = receiver()
  217. if receiver is not None:
  218. non_weak_receivers.append(receiver)
  219. else:
  220. non_weak_receivers.append(receiver)
  221. return non_weak_receivers
  222. def _remove_receiver(self, receiver=None):
  223. # Mark that the self.receivers list has dead weakrefs. If so, we will
  224. # clean those up in connect, disconnect and _live_receivers while
  225. # holding self.lock. Note that doing the cleanup here isn't a good
  226. # idea, _remove_receiver() will be called as side effect of garbage
  227. # collection, and so the call can happen while we are already holding
  228. # self.lock.
  229. self._dead_receivers = True
  230. def receiver(signal, **kwargs):
  231. """
  232. A decorator for connecting receivers to signals. Used by passing in the
  233. signal (or list of signals) and keyword arguments to connect::
  234. @receiver(post_save, sender=MyModel)
  235. def signal_receiver(sender, **kwargs):
  236. ...
  237. @receiver([post_save, post_delete], sender=MyModel)
  238. def signals_receiver(sender, **kwargs):
  239. ...
  240. """
  241. def _decorator(func):
  242. if isinstance(signal, (list, tuple)):
  243. for s in signal:
  244. s.connect(func, **kwargs)
  245. else:
  246. signal.connect(func, **kwargs)
  247. return func
  248. return _decorator