addons-server/lib/misc/safe_signals.py

52 строки
1.3 KiB
Python
Исходник Обычный вид История

"""
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
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)
# 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)
except Exception, err:
if do_raise:
raise
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__
unsafe_send = Signal.send
def start_the_machine():
# Monkeypatch!
Signal.send = safe_send
Signal.send_robust = safe_send