|
| 1 | +import random |
| 2 | + |
1 | 3 | from django.db import transaction
|
2 | 4 | from django.db.models.query import QuerySet
|
3 | 5 | from django.core.mail import EmailMultiAlternatives
|
4 | 6 | from django.utils import timezone
|
| 7 | +from django.conf import settings |
5 | 8 |
|
6 | 9 | from styleguide_example.core.exceptions import ApplicationError
|
7 | 10 |
|
|
11 | 14 | from styleguide_example.emails.tasks import email_send as email_send_task
|
12 | 15 |
|
13 | 16 |
|
| 17 | +@transaction.atomic |
| 18 | +def email_failed(email: Email) -> Email: |
| 19 | + if email.status != Email.Status.SENDING: |
| 20 | + raise ApplicationError(f"Cannot fail non-sending emails. Current status is {email.status}") |
| 21 | + |
| 22 | + email, _ = model_update( |
| 23 | + instance=email, |
| 24 | + fields=["status"], |
| 25 | + data={ |
| 26 | + "status": Email.Status.FAILED |
| 27 | + } |
| 28 | + ) |
| 29 | + return email |
| 30 | + |
| 31 | + |
14 | 32 | @transaction.atomic
|
15 | 33 | def email_send(email: Email) -> Email:
|
16 | 34 | if email.status != Email.Status.SENDING:
|
17 | 35 | raise ApplicationError(f"Cannot send non-ready emails. Current status is {email.status}")
|
18 | 36 |
|
| 37 | + if settings.EMAIL_SENDING_FAILURE_TRIGGER: |
| 38 | + failure_dice = random.uniform(0, 1) |
| 39 | + |
| 40 | + if failure_dice <= settings.EMAIL_SENDING_FAILURE_RATE: |
| 41 | + raise ApplicationError("Email sending failure triggered.") |
| 42 | + |
19 | 43 | subject = email.subject
|
20 | 44 | from_email = "styleguide-example@hacksoft.io"
|
21 | 45 | to = email.to
|
@@ -45,7 +69,7 @@ def email_send_all(emails: QuerySet[Email]):
|
45 | 69 |
|
46 | 70 | We don't want to decorate with @transaction.atomic,
|
47 | 71 | since we are executing updates, 1 by 1, in a separate atomic block,
|
48 |
| - so we can trigger transaction.on_commit for each email. |
| 72 | + so we can trigger transaction.on_commit for each email, separately. |
49 | 73 | """
|
50 | 74 | for email in emails:
|
51 | 75 | with transaction.atomic():
|
|
0 commit comments