Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Refactor the Code as a Celery Task

00:00 Refactoring to use tasks To start the refactoring, head back to, where the original email sending code was, and refactor. Send email so that it calls send_feedback_email_task.

00:16 Instead of handling the email sending code logic in send_email, you moved it to send_feedback_email_task in

00:21 This means you can remove the now redundant imports of sleep and django.core.mail.send_mail. You now import send_feedback_email_task

00:34 from feedback.tasks.

00:54 Here you call .delay() on send_feedback_email_task, and pass it the submitted form data fetched from .clean_data as arguments.

01:03 Note that calling .delay() is the quickest way to send a task message to Celery. This method is a shortcut to the more powerful .apply_async(), which additionally supports execution options for fine-tuning your task message.

01:18 If you wanted to use .apply_async(), then the code to achieve the same as just seen would be slightly more verbose. While .delay() is the better choice in a straightforward task message such as this, you’ll benefit from many execution options with .apply_async() such as countdown and retry.

01:35 But in this case, we’ll revert back to the code using .delay().

01:41 With these changes applied in and, you are all done refactoring the main chunk of work to run asynchronous tasks with Django and Celery. The setup rather than the actual code that you need to write is the key.

01:55 But the big question is, does it work? Do the emails still go out and does the Django app remain responsive? In the meantime, you’ll find out in the next section of the course where you test your asynchronous task.

Become a Member to join the conversation.