from django.db.models.signals import post_save,pre_delete from django.dispatch import receiver from eventplanner.models import Event, EventParticipation from django.contrib.auth.models import User import eventplanner_gcal.models class SignalLock: def __init__(self): self.locked=False def __enter__(self): if self.locked: return False self.locked=True return True def __exit__(self, type, value, traceback): self.locked=False def isLocked(self): return self.locked signalLock = SignalLock() @receiver( post_save, sender=User ) def user_changed( **kwargs ): if not signalLock.isLocked(): with signalLock: eventplanner_gcal.models.syncGCalEvents() @receiver( post_save,sender= Event) def event_post_save_handler( **kwargs): if not signalLock.isLocked(): with signalLock: event = kwargs['instance'] created = kwargs['created'] if created: print("Creating Gcal event") eventplanner_gcal.models.createGCalEvent( event ).execute() else: print( "Updating Gcal event") eventplanner_gcal.models.updateGCalEvent( event ).execute() @receiver( pre_delete,sender= Event) def event_pre_delete_handler( **kwargs): if not signalLock.isLocked(): with signalLock: event = kwargs['instance'] print ("Deleting GCAL event") eventplanner_gcal.models.deleteGCalEvent( event ).execute() @receiver( post_save, sender=EventParticipation ) def participation_post_save_handler( **kwargs): if not signalLock.isLocked(): with signalLock: participation = kwargs['instance'] print("Participation post save -> update gcal") eventplanner_gcal.models.updateGCalEvent( participation.event ).execute() # -------------- For management commands ------------------------ def stopAllGCalSubscriptions(): if not signalLock.isLocked(): with signalLock: eventplanner_gcal.models.stopAllGCalSubscriptions() def checkGCalSubscription(): if not signalLock.isLocked(): with signalLock: eventplanner_gcal.models.checkGCalSubscription() def deleteAllGCalEvents(): if not signalLock.isLocked(): with signalLock: eventplanner_gcal.models.deleteAllGCalEvents() def syncGCalEvents(): if not signalLock.isLocked(): with signalLock: eventplanner_gcal.models.syncGCalEvents()