Przeglądaj źródła

Added a 2 second timeout for sending error e-mails. Closes #222

Ask Solem 14 lat temu
rodzic
commit
37c683ffc9
2 zmienionych plików z 25 dodań i 14 usunięć
  1. 1 1
      celery/tests/test_worker_job.py
  2. 24 13
      celery/utils/mail.py

+ 1 - 1
celery/tests/test_worker_job.py

@@ -323,7 +323,7 @@ class test_TaskRequest(unittest.TestCase):
         x = tw.success_msg % {"name": tw.task_name,
                               "id": tw.task_id,
                               "return_value": 10,
-                              "runtime": 0.1376}
+                              "runtime": 0.3641}
         self.assertTrue(x)
         x = tw.error_msg % {"name": tw.task_name,
                            "id": tw.task_id,

+ 24 - 13
celery/utils/mail.py

@@ -1,3 +1,4 @@
+import sys
 import smtplib
 import warnings
 
@@ -6,6 +7,8 @@ try:
 except ImportError:
     from email.MIMEText import MIMEText
 
+supports_timeout = sys.version_info > (2, 5)
+
 
 class SendmailWarning(UserWarning):
     """Problem happened while sending the e-mail message."""
@@ -37,23 +40,31 @@ class Message(object):
 
 class Mailer(object):
 
-    def __init__(self, host="localhost", port=0, user=None, password=None):
+    def __init__(self, host="localhost", port=0, user=None, password=None,
+            timeout=2):
         self.host = host
         self.port = port
         self.user = user
         self.password = password
+        self.timeout = timeout
+
+    def send(self, message):
+        if supports_timeout:
+            self._send(message, timeout=self.timeout)
+        else:
+            import socket
+            old_timeout = socket.getdefaulttimeout()
+            socket.setdefaulttimeout(self.timeout)
+            try:
+                self._send(message)
+            finally:
+                socket.setdefaulttimeout(old_timeout)
 
-    def send(self, message, fail_silently=False):
-        try:
-            client = smtplib.SMTP(self.host, self.port)
+    def _send(self, message, **kwargs):
+        client = smtplib.SMTP(self.host, self.port, **kwargs)
 
-            if self.user and self.password:
-                client.login(self.user, self.password)
+        if self.user and self.password:
+            client.login(self.user, self.password)
 
-            client.sendmail(message.sender, message.to, str(message))
-            client.quit()
-        except Exception, exc:
-            if not fail_silently:
-                raise
-            warnings.warn(SendmailWarning(
-                "E-mail could not be sent: %r %r" % (exc, message)))
+        client.sendmail(message.sender, message.to, str(message))
+        client.quit()