Adding asynchronous tasks to your application

We are going to create an asynchronous task to send an email notification to our users when they place an order. The convention is to include asynchronous tasks for your application in a tasks module within your application directory.

Create a new file inside the orders application and name it tasks.py. This is the place where Celery will look for asynchronous tasks. Add the following code to it:

from celery import taskfrom django.core.mail import send_mailfrom .models import Order@taskdef order_created(order_id):    """    Task to send an e-mail notification when an order is     successfully created.    """    order = Order.objects.get(id=order_id)    subject = 'Order nr. {}'.format(order.id) message = 'Dear {},\n\nYou ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.