Monday, April 9, 2012

Django signals

Simplificated version of Django signal.connect function, but it insert the receiver as the first receiver of the list. The default behavior is to add it in the final. To this algorithm makes sense, it must be called just once per signal, so use it in very special cases. Código:

def connect_as_first_signal(signal, receiver, sender=None, dispatch_uid=None): "Similar to signal.connect(receiver, sender=sender), but put the receiver as the first element in the list." from django.dispatch.dispatcher import _make_id if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) signal.lock.acquire() try: for r_key, _ in signal.receivers: if r_key == lookup_key: break else: signal.receivers.insert(0, (lookup_key, receiver)) finally: signal.lock.release() Usage: from django.db.models.signals import pre_save connect_as_first_signal(pre_save, SUA_FUNCAO_DE_CALL_BACK, sender=SEU_SENDER, dispatch_uid=SEU_ID)

No comments:

Post a Comment