1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
| import logging import threading import weakref
from django.utils.inspect import func_accepts_kwargs
logger = logging.getLogger("django.dispatch")
def _make_id(target): """ 对传递进来的函数生成对应的标识,这里使用了 id 函数 """
if hasattr(target, "__func__"): return (id(target.__self__), id(target.__func__)) return id(target)
NONE_ID = _make_id(None)
NO_RECEIVERS = object()
class Signal: """ Base class for all signals
Internal attributes:
receivers { receiverkey (id) : weakref(receiver) } """
def __init__(self, use_caching=False): """ 创建一个新的信号对象
Create a new signal. """ self.receivers = []
self.lock = threading.Lock()
self.use_caching = use_caching
self.sender_receivers_cache = weakref.WeakKeyDictionary() if use_caching else {}
self._dead_receivers = False
def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): """ 用于将信号接收器(receiver)注册到信号对象(signal)。接收器是一个函数,当信号 被发送时,对应发送者所有对应的接收器将被触发
Connect receiver to sender for signal.
Arguments:
receiver 接收器
接收器是一个用来接收信号的函数或者对象的方法,接收器必须可 hash。 A function or an instance method which is to receive signals. Receivers must be hashable objects.
当 weak 为 True 时,接收器一定可以被弱引用。 If weak is True, then receiver must be weak referenceable.
接收器必须可以接受关键字参数 Receivers must be able to accept keyword arguments.
如果一个接收器(A) 连接时,使用了 dispatch_uid 参数,那么如果其他接收器(B)连接时, 使用了同样的 dispatch_uid,那么接收器(A)将不会被添加,即 dispatch_uid 不能重复。 If a receiver is connected with a dispatch_uid argument, it will not be added if another receiver was already connected with that dispatch_uid.
sender 发送者 一个用于触发接收器响应的对象。如果为 sender 设置一个具体的对象,那么只有来自该 对象发送的信号才会触发接收器。如果省略 sender 参数,那么该接收器将响应所有发送者的信号。 在 django 的调用中,多处基本上都是类。例如 request_started 信号对应的发送者是 class 'django.core.handlers.wsgi.WSGIHandler'
The sender to which the receiver should respond. Must either be a Python object, or None to receive events from any sender.
weak 弱引用 是否使用对接收器的弱引用。默认情况下,该模块将尝试使用弱引用来引用接收器。 如果这个参数为 false,那么将使用强引用
Whether to use weak references to the receiver. By default, the module will attempt to use weak references to the receiver objects. If this parameter is false, then strong references will be used.
dispatch_uid 在可能发送重复信号的情况下,信号接收器的唯一标识符
一个用于唯一地标识一个特定接收器对象的标识符,它通常是一个字符串,虽然它可以是 任何可哈希的东西。
An identifier used to uniquely identify a particular instance of a receiver. This will usually be a string, though it may be anything hashable. """ from django.conf import settings
if settings.configured and settings.DEBUG: if not callable(receiver): raise TypeError("Signal receivers must be callable.") if not func_accepts_kwargs(receiver): raise ValueError( "Signal receivers must accept keyword arguments (**kwargs)." )
if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender))
if weak: ref = weakref.ref receiver_object = receiver if hasattr(receiver, "__self__") and hasattr(receiver, "__func__"): ref = weakref.WeakMethod receiver_object = receiver.__self__ receiver = ref(receiver) weakref.finalize(receiver_object, self._remove_receiver)
with self.lock: self._clear_dead_receivers() if not any(r_key == lookup_key for r_key, _ in self.receivers): self.receivers.append((lookup_key, receiver)) self.sender_receivers_cache.clear()
def disconnect(self, receiver=None, sender=None, dispatch_uid=None): """ 为指定的发送者对象移除对应的接收器
Disconnect receiver from sender for signal.
如果使用了弱引用,disconnect 函数不需要调用。因为弱引用的接收器会自动移除。
If weak references are used, disconnect need not be called. The receiver will be removed from dispatch automatically.
Arguments:
receiver The registered receiver to disconnect. May be none if dispatch_uid is specified.
sender The registered sender to disconnect
dispatch_uid the unique identifier of the receiver to disconnect """ if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender))
disconnected = False with self.lock: self._clear_dead_receivers() for index in range(len(self.receivers)): (r_key, _) = self.receivers[index] if r_key == lookup_key: disconnected = True del self.receivers[index] break self.sender_receivers_cache.clear()
return disconnected
def has_listeners(self, sender=None): """是否存在指定发送者有效的接收器""" return bool(self._live_receivers(sender))
def send(self, sender, **named): """ 发送信号到指定发送者的接收器中
Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send, terminating the dispatch loop. So it's possible that all receivers won't be called if an error is raised.
Arguments:
sender The sender of the signal. Either a specific object or None.
named Named arguments which will be passed to receivers.
Return a list of tuple pairs [(receiver, response), ... ]. """ if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return []
return [(receiver, receiver(signal=self, sender=sender, **named)) for receiver in self._live_receivers(sender)]
def send_robust(self, sender, **named): """ Send signal from sender to all connected receivers catching errors.
Arguments:
sender The sender of the signal. Can be any Python object (normally one registered with a connect if you actually want something to occur).
named Named arguments which will be passed to receivers.
Return a list of tuple pairs [(receiver, response), ... ].
If any receiver raises an error (specifically any subclass of Exception), return the error instance as the result for that receiver. """ if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return []
responses = [] for receiver in self._live_receivers(sender): try: response = receiver(signal=self, sender=sender, **named) except Exception as err: logger.error( "Error calling %s in Signal.send_robust() (%s)", receiver.__qualname__, err, exc_info=err, ) responses.append((receiver, err)) else: responses.append((receiver, response)) return responses
def _clear_dead_receivers(self): """清除无效的接收器""" if self._dead_receivers: self._dead_receivers = False
self.receivers = [ r for r in self.receivers if not (isinstance(r[1], weakref.ReferenceType) and r[1]() is None) ]
def _live_receivers(self, sender): """ 根据指定的发送者获取接收器列表
Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only live receivers. """ receivers = None
if self.use_caching and not self._dead_receivers: receivers = self.sender_receivers_cache.get(sender) if receivers is NO_RECEIVERS: return []
if receivers is None: with self.lock: self._clear_dead_receivers() senderkey = _make_id(sender) receivers = []
for (receiverkey, r_senderkey), receiver in self.receivers: if r_senderkey == NONE_ID or r_senderkey == senderkey: receivers.append(receiver)
if self.use_caching: if not receivers: self.sender_receivers_cache[sender] = NO_RECEIVERS else: self.sender_receivers_cache[sender] = receivers non_weak_receivers = []
for receiver in receivers: if isinstance(receiver, weakref.ReferenceType): receiver = receiver() if receiver is not None: non_weak_receivers.append(receiver) else: non_weak_receivers.append(receiver) return non_weak_receivers
def _remove_receiver(self, receiver=None): """ 当弱引用引用的对象不存在时,给当前的信号标识存在无效的接收器
标注 self.receivers 存在无效的弱引用。如果存在无效的弱引用, 将在 connect、disconnect 和 _live_receivers 中清理这些 无效的弱引用对象。 """
self._dead_receivers = True
def receiver(signal, **kwargs): """ 连接接收器到信号的装饰器,其内部实际上是对 connect 方法的包装,使用装饰器看起来更直观一些。
A decorator for connecting receivers to signals. Used by passing in the signal (or list of signals) and keyword arguments to connect::
@receiver(post_save, sender=MyModel) def signal_receiver(sender, **kwargs): ...
@receiver([post_save, post_delete], sender=MyModel) def signals_receiver(sender, **kwargs): ... """
def _decorator(func): if isinstance(signal, (list, tuple)): for s in signal: s.connect(func, **kwargs) else: signal.connect(func, **kwargs) return func
return _decorator
|