Browse Source

Add a context-manager to temporary disable maillist sync command

Jocelyn Delalande 6 years ago
parent
commit
a54cfd12f1
1 changed files with 38 additions and 6 deletions
  1. 38 6
      maillists/models.py

+ 38 - 6
maillists/models.py

@@ -2,6 +2,7 @@
 
 from __future__ import unicode_literals
 
+from contextlib import contextmanager
 import subprocess
 
 from django.conf import settings
@@ -84,20 +85,18 @@ class MaillingList(models.Model):
                         out_stderr.decode('utf-8')))
 
 
-@receiver(post_save, sender=MaillingListSubscription)
 def push_new_subscription(sender, instance, created, raw, *args, **kwargs):
     if raw:
         print("The synchronization of mailling list with Coin was not performed, please launch it by hand in the admin interface.")
-    else:
+    elif not getattr(sender, 'skip_sync', False):
         instance.maillinglist.sync_to_list_server()
 
-@receiver(post_delete, sender=MaillingListSubscription)
-def push_remove_subscription(sender, instance, *args, **kwargs):
-    instance.maillinglist.sync_to_list_server()
 
+def push_remove_subscription(sender, instance, *args, **kwargs):
+    if not getattr(sender, 'skip_sync', False):
+        instance.maillinglist.sync_to_list_server()
 
 
-@receiver(pre_save, sender=Member)
 def store_previous_email(sender, instance, *args, **kwargs):
     """Record the email address for post_save handler
 
@@ -131,3 +130,36 @@ def update_an_email_address(sender, instance, *args, **kwargs):
     # except SyncCommandError as e:
     #     print("error", e)
     # we cannot send a message because we don't have the request
+
+
+SIGNALS = [
+    (Member, pre_save, store_previous_email),
+    (Member, post_save, update_an_email_address),
+    (MaillingListSubscription, post_save, push_new_subscription),
+    (MaillingListSubscription, post_delete, push_remove_subscription),
+]
+
+
+def connect_signals():
+    for sender, signal, receiver in SIGNALS:
+        signal.connect(sender=sender, receiver=receiver)
+
+
+def disconnect_signals():
+    for sender, signal, receiver in SIGNALS:
+        signal.disconnect(sender=sender, receiver=receiver)
+
+
+# Do it once
+connect_signals()
+
+
+@contextmanager
+def skip_maillist_sync():
+    """ Allows to skip temporary signals
+    """
+    disconnect_signals()
+    try:
+        yield
+    finally:
+        connect_signals()