Multitasking In Django: Celery

Adding the ability of Multitasking in Django/Python app can improve its efficiency by several times as it frees up the CPU to perform other operations. The process to achieve this is made very simple by using Celery.

Image From Pexels

It is perfect for performing backend tasks. While continuing on with the visible processes to better engage one’s customers. This makes the website perform much faster.

Download Base App for following along.

Implementation and Setup

Step #1. Install and Setup RabbitMQ local sever

Go to Link and setup RabbitMQ local server.

Step #2. Prepare the Django App

Start the Django App and in the main app add a celery.py file with the following code.

import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoCelery.settings')

app = Celery('DjangoCelery')

# 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}')

Note that the name “DjangoCelery” has to be changed with the name of your Django App if you are customizing the project.

You also need to paste the following code in the __init__.py file to initiate the celery app when you run the app.

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app',)

Go to the settings.py file of the Django App and add the following parameters.

Note. If you are using a server to handle the requests add the following lines in your code.

CELERY_BROKER_URL = 'URL from RabitMQ'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'

Note. If you are using celery locally run the following commands.

celery -A DjangoCelery worker -l info

Open the celery command prompt using the following command open the the root directory of the project.

pip install redis

python manage.py runserver

Now in an alternate command prompt run

celery -A DjangoCelery worker -l

Note that the name “DjangoCelery” has to be changed with the name of your Django Project.

Step #4. Setup Mailing Code

Go to the settings.py file and add the following fields to configure the Mailing functionality. Note that Less Secured Apps are allowed in your Email.

EMAIL_HOST = 'smtp.service_provider.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'Email'
EMAIL_HOST_PASSWORD = 'Password'
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True

Go to the Mailing App in your Django App and create a file called tasks.py file there and add the following code to send the mail.

from celery import shared_task 
from django.core.mail import send_mail
from time import sleep

@shared_task
def send_email_task(subject,message,fromMail,toArr):
    send_mail(subject,message,fromMail,toArr)
    return None

Next you need to setup the views.py file to call the code above.

Final Project

Template from CodePen:
 

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *