Skip to content

Commit

Permalink
Add send_mass_mail_async
Browse files Browse the repository at this point in the history
  • Loading branch information
TheSuncatcher222 committed Nov 26, 2023
1 parent d2eb123 commit 65acd80
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
11 changes: 10 additions & 1 deletion backend/api/v1/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,11 @@
)
from api.v1.utils import create_secret_code, send_mail
from info.models import Appeal, News, NewsComment
from info.tasks import send_mass_mail_async
from urban_utopia_2024.app_data import (
APPEAL_STAGE_COMPLETED,
APPEAL_STAGE_COMPLETED, CITE_DOMAIN,
EMAIL_CONFIRM_EMAIL_SUBJECT, EMAIL_CONFIRM_EMAIL_TEXT,
EMAIL_NEWS_SUBJECT, EMAIL_NEWS_TEXT,
)
from user.models import User

Expand Down Expand Up @@ -220,6 +222,13 @@ def create(self, request, *args, **kwargs):
response_serializer: serializers = NewsSerializer(
instance=news_instance
)
send_mass_mail_async.delay(
subject=EMAIL_NEWS_SUBJECT,
message=EMAIL_NEWS_TEXT.format(
category=news_instance.category,
link=f'https://{CITE_DOMAIN}/api/v1/news/{news_instance.id}/',
),
)
return Response(
data=response_serializer.data,
status=status.HTTP_201_CREATED
Expand Down
38 changes: 38 additions & 0 deletions backend/info/tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from celery import group, shared_task

from api.v1.utils import send_mail
from urban_utopia_2024.app_data import CHUNK_EMAIL
from user.models import User


@shared_task
def send_mass_mail(subject: str, message: str, user_emails: list[str]) -> None:
"""Отправляет письма указанным адресатам в user_emails."""
for email in user_emails:
send_mail(subject=subject, message=message, to=(email,))
return


@shared_task
def send_mass_mail_async(subject: str, message: str) -> None:
"""Задача по рассылке писем пользователям."""
user_emails: list[str] = User.objects.filter(
is_staff=False,
is_municipal=False,
).values_list(
'email',
flat=True,
)
user_groups: list[list[str]] = [
user_emails[i:(i+CHUNK_EMAIL)] for
i in range(0, len(user_emails), CHUNK_EMAIL)
]
celery_group: group = group(
send_mass_mail.s(
subject=subject,
message=message,
user_emails=user_group
) for user_group in user_groups
)
celery_group.apply_async()
return

0 comments on commit 65acd80

Please sign in to comment.