Skip to content

Commit 4b5170e

Browse files
committed
ee
1 parent 1c3bfc7 commit 4b5170e

File tree

1 file changed

+31
-31
lines changed

1 file changed

+31
-31
lines changed

backend/notifications/tasks.py

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from django.db import transaction
22

3-
from celery.exceptions import MaxRetriesExceededError
43
import logging
54
from uuid import uuid4
65
from notifications.models import SentEmail
@@ -11,53 +10,54 @@
1110
logger = logging.getLogger(__name__)
1211

1312

13+
def send_pending_email_failed(self, task_id, args, kwargs, einfo):
14+
sent_email_id = args[0]
15+
16+
sent_email = SentEmail.objects.get(id=sent_email_id)
17+
sent_email.mark_as_failed()
18+
logger.error(
19+
"Failed to send email sent_email_id=%s",
20+
sent_email.id,
21+
)
22+
23+
1424
@app.task(
1525
bind=True,
26+
autoretry_for=(Exception,),
1627
retry_backoff=5,
1728
max_retries=5,
1829
default_retry_delay=2,
30+
on_failure=send_pending_email_failed,
1931
)
32+
@transaction.atomic()
2033
def send_pending_email(self, sent_email_id: int):
2134
logger.info(
22-
"Sending sent_email=%s (retry=%s of %s)",
35+
"Sending sent_email=%s (attempt=%s of %s)",
2336
sent_email_id,
2437
self.request.retries,
2538
self.max_retries,
2639
)
2740

28-
try:
29-
with transaction.atomic():
30-
sent_email = (
31-
SentEmail.objects.select_for_update(skip_locked=True)
32-
.pending()
33-
.filter(id=sent_email_id)
34-
.first()
35-
)
41+
sent_email = (
42+
SentEmail.objects.select_for_update(skip_locked=True)
43+
.pending()
44+
.filter(id=sent_email_id)
45+
.first()
46+
)
3647

37-
if not sent_email:
38-
return
48+
if not sent_email:
49+
return
3950

40-
email_backend_connection = get_connection()
51+
email_backend_connection = get_connection()
4152

42-
message_id = send_email(sent_email, email_backend_connection)
43-
sent_email.mark_as_sent(message_id)
53+
message_id = send_email(sent_email, email_backend_connection)
54+
sent_email.mark_as_sent(message_id)
4455

45-
logger.info(
46-
"Email sent_email_id=%s sent with message_id=%s",
47-
sent_email.id,
48-
message_id,
49-
)
50-
except Exception as e:
51-
try:
52-
raise self.retry(exc=e)
53-
except MaxRetriesExceededError:
54-
sent_email = SentEmail.objects.get(id=sent_email_id)
55-
sent_email.mark_as_failed()
56-
logger.error(
57-
"Failed to send email sent_email_id=%s",
58-
sent_email.id,
59-
)
60-
return
56+
logger.info(
57+
"Email sent_email_id=%s sent with message_id=%s",
58+
sent_email.id,
59+
message_id,
60+
)
6161

6262

6363
def send_email(sent_email, email_backend_connection):

0 commit comments

Comments
 (0)