Skip to content

Commit

Permalink
Offload initial email task
Browse files Browse the repository at this point in the history
- Prevent blocking on email task
- Allow worker to try multiple times
- Don't pass 500 error back to form validation
  • Loading branch information
SchrodingersGat committed Nov 2, 2024
1 parent 4308f0c commit fd99f3c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/backend/InvenTree/InvenTree/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,7 @@ def validate(self, attrs):
def create(self, validated_data):
"""Send an e email to the user after creation."""
from InvenTree.helpers_model import get_base_url
from InvenTree.tasks import email_user, offload_task

base_url = get_base_url()

Expand All @@ -527,8 +528,12 @@ def create(self, validated_data):
if base_url:
message += f'\n\nURL: {base_url}'

subject = _('Welcome to InvenTree')

# Send the user an onboarding email (from current site)
instance.email_user(subject=_('Welcome to InvenTree'), message=message)
offload_task(
email_user, instance.pk, str(subject), str(message), force_async=True
)

return instance

Expand Down
12 changes: 12 additions & 0 deletions src/backend/InvenTree/InvenTree/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from typing import Callable, Optional

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import AppRegistryNotReady
from django.core.management import call_command
from django.db import DEFAULT_DB_ALIAS, connections
Expand Down Expand Up @@ -693,3 +694,14 @@ def set_pending_migrations(n: int):
# We should be current now - triggering full reload to make sure all models
# are loaded fully in their new state.
registry.reload_plugins(full_reload=True, force_reload=True, collect=True)


def email_user(user_id: int, subject: str, message: str) -> None:
"""Send a message to a user."""
try:
user = get_user_model().objects.get(pk=user_id)
except Exception:
logger.warning('User <%s> not found - cannot send welcome message', user_id)
return

user.email_user(subject=subject, message=message)

0 comments on commit fd99f3c

Please sign in to comment.