How to Use Celery with Django in Python

Install the necessary packages

In order to use Celery with Django in Python, you need to install a few packages. First, you will need to install Celery, which is an asynchronous task queue based on distributed message passing. You can do this by running the following command:

pip install celery
. Additionally, you will also need to install the Redis server for Celery's backend storage and messaging system. To do this, run the following command:
sudo apt-get update && sudo apt-get install redis-server
. Finally, you will also need to install Django itself if it is not already installed on your machine; simply run
pip3 install django==3.0.* 
. Once all of these packages are installed correctly, you are ready to configure Celery for use with Django.

Configure Celery for use with Django

In order to configure Celery for use with Django, you need to install the necessary packages. This includes Celery, Django, and a message broker such as RabbitMQ or Redis. Once these packages are installed, you can create a tasks module in your application directory that will contain all of your Celery tasks.

# myapp/tasks.py
from celery import shared_task

 @shared_task
def add(x, y):
    return x + y 

Next, you need to configure the settings in your project's settings file (settings.py) so that it knows where to find the task module and which message broker to use:

# myproject/settings.py   BROKER_URL = 'amqp://localhost'   CELERY_RESULT_BACKEND = 'redis://localhost'   CELERY_IMPORTS = ('myapp.tasks', ) 

Finally, you can start up the worker process by running the following command from within your project directory:

$ celery -A myproject worker --loglevel=info 
Create a tasks module in your application directory

In this step, you will create a tasks module in the application directory of your Django project. This is where all the Celery related code will be stored. To do this, open up your terminal and navigate to the root folder of your Django project.

cd /path/to/your/django-project

Once inside the root folder, create a new file called "tasks.py". Inside this file, add the following code:

from celery import shared_task

@shared_task
def my_background_task():
    # Your background task logic goes here!   

This is just an example of how to set up a basic Celery task for use with Django. You can find more information about setting up and using Celery with Django on their official website here. Once you have finished configuring Celery for use with Django, you are ready to move onto creating tasks.

Useful Links