Sobes.tech
Junior — Middle

How is the integration of Celery with Django carried out and how does the task exchange between them occur?

sobes.tech AI

Answer from AI

Integration of Celery with Django usually occurs through creating a separate Celery configuration file in the Django project, where the Celery object is configured with a message broker (e.g., Redis or RabbitMQ). In Django's settings.py, broker parameters and other settings are specified.

Task exchange happens via the message broker: Django sends tasks to the queue, and Celery workers pick them up and execute asynchronously. Tasks are described as functions decorated with @shared_task or @app.task.

Example configuration:

# myproject/celery.py
from celery import Celery
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
app = Celery('myproject')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

In the application's tasks.py:

from celery import shared_task

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

In Django code, you can call the task asynchronously:

add.delay(4, 6)

Thus, Django sends the task to the broker, the Celery worker receives it, and executes it.