PageRenderTime 51ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/DjamboServerWithProcessing/django/django/dispatch/dispatcher.py

https://gitlab.com/benji-bou/urotechchallenge-Serenity
Python | 317 lines | 204 code | 21 blank | 92 comment | 29 complexity | c60a1986f3bebf3e495b1403d465d3e8 MD5 | raw file
  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. a Python object, 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.", RemovedInDjango20Warning, stacklevel=2)
  118. if dispatch_uid:
  119. lookup_key = (dispatch_uid, _make_id(sender))
  120. else:
  121. lookup_key = (_make_id(receiver), _make_id(sender))
  122. disconnected = False
  123. with self.lock:
  124. self._clear_dead_receivers()
  125. for index in range(len(self.receivers)):
  126. (r_key, _) = self.receivers[index]
  127. if r_key == lookup_key:
  128. disconnected = True
  129. del self.receivers[index]
  130. break
  131. self.sender_receivers_cache.clear()
  132. return disconnected
  133. def has_listeners(self, sender=None):
  134. return bool(self._live_receivers(sender))
  135. def send(self, sender, **named):
  136. """
  137. Send signal from sender to all connected receivers.
  138. If any receiver raises an error, the error propagates back through send,
  139. terminating the dispatch loop. So it's possible that all receivers
  140. won't be called if an error is raised.
  141. Arguments:
  142. sender
  143. The sender of the signal. Either a specific object or None.
  144. named
  145. Named arguments which will be passed to receivers.
  146. Returns a list of tuple pairs [(receiver, response), ... ].
  147. """
  148. if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
  149. return []
  150. return [
  151. (receiver, receiver(signal=self, sender=sender, **named))
  152. for receiver in self._live_receivers(sender)
  153. ]
  154. def send_robust(self, sender, **named):
  155. """
  156. Send signal from sender to all connected receivers catching errors.
  157. Arguments:
  158. sender
  159. The sender of the signal. Can be any python object (normally one
  160. registered with a connect if you actually want something to
  161. occur).
  162. named
  163. Named arguments which will be passed to receivers. These
  164. arguments must be a subset of the argument names defined in
  165. providing_args.
  166. Return a list of tuple pairs [(receiver, response), ... ]. May raise
  167. DispatcherKeyError.
  168. If any receiver raises an error (specifically any subclass of
  169. Exception), the error instance is returned as the result for that
  170. receiver. The traceback is always attached to the error at
  171. ``__traceback__``.
  172. """
  173. if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
  174. return []
  175. # Call each receiver with whatever arguments it can accept.
  176. # Return a list of tuple pairs [(receiver, response), ... ].
  177. responses = []
  178. for receiver in self._live_receivers(sender):
  179. try:
  180. response = receiver(signal=self, sender=sender, **named)
  181. except Exception as err:
  182. if not hasattr(err, '__traceback__'):
  183. err.__traceback__ = sys.exc_info()[2]
  184. responses.append((receiver, err))
  185. else:
  186. responses.append((receiver, response))
  187. return responses
  188. def _clear_dead_receivers(self):
  189. # Note: caller is assumed to hold self.lock.
  190. if self._dead_receivers:
  191. self._dead_receivers = False
  192. new_receivers = []
  193. for r in self.receivers:
  194. if isinstance(r[1], weakref.ReferenceType) and r[1]() is None:
  195. continue
  196. new_receivers.append(r)
  197. self.receivers = new_receivers
  198. def _live_receivers(self, sender):
  199. """
  200. Filter sequence of receivers to get resolved, live receivers.
  201. This checks for weak references and resolves them, then returning only
  202. live receivers.
  203. """
  204. receivers = None
  205. if self.use_caching and not self._dead_receivers:
  206. receivers = self.sender_receivers_cache.get(sender)
  207. # We could end up here with NO_RECEIVERS even if we do check this case in
  208. # .send() prior to calling _live_receivers() due to concurrent .send() call.
  209. if receivers is NO_RECEIVERS:
  210. return []
  211. if receivers is None:
  212. with self.lock:
  213. self._clear_dead_receivers()
  214. senderkey = _make_id(sender)
  215. receivers = []
  216. for (receiverkey, r_senderkey), receiver in self.receivers:
  217. if r_senderkey == NONE_ID or r_senderkey == senderkey:
  218. receivers.append(receiver)
  219. if self.use_caching:
  220. if not receivers:
  221. self.sender_receivers_cache[sender] = NO_RECEIVERS
  222. else:
  223. # Note, we must cache the weakref versions.
  224. self.sender_receivers_cache[sender] = receivers
  225. non_weak_receivers = []
  226. for receiver in receivers:
  227. if isinstance(receiver, weakref.ReferenceType):
  228. # Dereference the weak reference.
  229. receiver = receiver()
  230. if receiver is not None:
  231. non_weak_receivers.append(receiver)
  232. else:
  233. non_weak_receivers.append(receiver)
  234. return non_weak_receivers
  235. def _remove_receiver(self, receiver=None):
  236. # Mark that the self.receivers list has dead weakrefs. If so, we will
  237. # clean those up in connect, disconnect and _live_receivers while
  238. # holding self.lock. Note that doing the cleanup here isn't a good
  239. # idea, _remove_receiver() will be called as side effect of garbage
  240. # collection, and so the call can happen while we are already holding
  241. # self.lock.
  242. self._dead_receivers = True
  243. def receiver(signal, **kwargs):
  244. """
  245. A decorator for connecting receivers to signals. Used by passing in the
  246. signal (or list of signals) and keyword arguments to connect::
  247. @receiver(post_save, sender=MyModel)
  248. def signal_receiver(sender, **kwargs):
  249. ...
  250. @receiver([post_save, post_delete], sender=MyModel)
  251. def signals_receiver(sender, **kwargs):
  252. ...
  253. """
  254. def _decorator(func):
  255. if isinstance(signal, (list, tuple)):
  256. for s in signal:
  257. s.connect(func, **kwargs)
  258. else:
  259. signal.connect(func, **kwargs)
  260. return func
  261. return _decorator