2010-09-25 04:17:03 +04:00
|
|
|
"""
|
|
|
|
A monkeypatch for ``django.dispatch`` to send signals safely.
|
|
|
|
|
|
|
|
Usage::
|
|
|
|
|
|
|
|
>>> import safe_signals
|
|
|
|
>>> safe_signals.start_the_machine()
|
|
|
|
|
|
|
|
``django.dispatch.Signal.send`` is replaced with a safer function that catches
|
|
|
|
and logs errors. It's like ``Signal.send_robust`` but with logging.
|
|
|
|
|
|
|
|
"""
|
|
|
|
import logging
|
|
|
|
|
|
|
|
from django.dispatch.dispatcher import Signal, _make_id
|
2012-09-24 08:15:39 +04:00
|
|
|
from django.conf import settings
|
2012-09-24 05:20:01 +04:00
|
|
|
|
2010-09-25 04:17:03 +04:00
|
|
|
|
|
|
|
log = logging.getLogger('signals')
|
|
|
|
|
|
|
|
|
|
|
|
def safe_send(self, sender, **named):
|
|
|
|
responses = []
|
|
|
|
if not self.receivers:
|
|
|
|
return responses
|
|
|
|
|
2012-09-24 05:32:52 +04:00
|
|
|
do_raise = getattr(settings, 'RAISE_ON_SIGNAL_ERROR', False)
|
2012-09-24 05:20:01 +04:00
|
|
|
|
2010-09-25 04:17:03 +04:00
|
|
|
# Call each receiver with whatever arguments it can accept.
|
|
|
|
# Return a list of tuple pairs [(receiver, response), ... ].
|
|
|
|
for receiver in self._live_receivers(_make_id(sender)):
|
|
|
|
try:
|
2013-04-18 22:11:11 +04:00
|
|
|
response = receiver(signal=self, sender=sender, **named)
|
2010-09-25 04:17:03 +04:00
|
|
|
except Exception, err:
|
2012-09-24 05:20:01 +04:00
|
|
|
if do_raise:
|
|
|
|
raise
|
2010-09-25 04:17:03 +04:00
|
|
|
log.error('Error calling signal', exc_info=True)
|
|
|
|
responses.append((receiver, err))
|
|
|
|
else:
|
|
|
|
responses.append((receiver, response))
|
|
|
|
return responses
|
|
|
|
|
|
|
|
|
|
|
|
safe_send.__doc__ = Signal.send_robust.__doc__
|
2010-09-25 04:39:51 +04:00
|
|
|
unsafe_send = Signal.send
|
2010-09-25 04:17:03 +04:00
|
|
|
|
|
|
|
|
|
|
|
def start_the_machine():
|
|
|
|
# Monkeypatch!
|
|
|
|
Signal.send = safe_send
|
|
|
|
Signal.send_robust = safe_send
|