Sending asynchronous email with celery in django project

Viewed 627

have a good day. I watched how to install celery to my django project. From start to this step there is no problem actually. My purpose is when i submit a form from my web site, that request takes too much time with sending email and submitting. I installed celery for asynchronous tasks to send email seperately. My email sending function works fine without a delay. But i want to add a delay to it. Celery logs says the task is succeeded in bla-bla seconds but i got nothing in my email.

this is my celery.py file

import os

from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings')
os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1')
app = Celery('django_project')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()


@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')

this is my views.py

def kaiserdicke(request):
    successful_submit = check_newsletter_submission(request)
    if request.method == "POST":
        send_email_task.delay(
            'Information about Kaiser&Dicke',
            'Hello there!',
            'info @ xn - -denkmalgeschtztelofts - kic.de',
            [request.POST['email']]
                        )
        successful_submit = True
    return render(request, "denkmalgeschutztelofts/kaiserdicke.html",
                  {"successful_submit": successful_submit})

this is my tasks.py

from celery import shared_task
from time import sleep

from django.core.mail import send_mail


@shared_task
def sleepy(duration):
    sleep(duration)
    return None
@shared_task
def send_email_task(subject,message,sender,recipients):
    sleep(30)
    send_mail(
        subject,message,sender,recipients
    )
    return None

maybe some relevant codes from settings.py

CELERY_BROKER_URL = 'redis url'
CELERY_ACCCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'

EMAIL_HOST = 'smtp.yandex.ru'
EMAIL_HOST_USER = 'email'
EMAIL_HOST_PASSWORD = '******'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

from terminal of celery -A django_project worker -l info, i get Task denkmalgeschutztelofts.tasks.send_email_task succeeded in 0.03099999999994907s. I really need a hand on this. Thanks, have a nice day.

UPDATE: So i have done the delay part of my issue. But there is another problem. When i fill the email part of form then submit, i have got server 500 error. Why is that happening?

0 Answers
Related