0
0
Djangoframework~10 mins

Celery installation and setup in Django

Choose your learning style9 modes available
Introduction

Celery helps your Django app do tasks in the background. This means your app stays fast and can handle many jobs without waiting.

You want to send emails without making users wait.
You need to process large files or images after upload.
You want to run tasks regularly, like cleaning old data.
You want to handle slow tasks without freezing the website.
Syntax
Django
pip install celery

# In your Django project folder, create a celery.py file
from celery import Celery
import os

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

Replace your_project with your actual Django project name.

Celery uses a message broker like Redis or RabbitMQ to manage tasks.

Examples
Install Celery and Redis client to use Redis as the message broker.
Django
pip install celery redis
Basic setup of Celery in a Django project named myproject.
Django
# celery.py in your Django project
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()
Tells Celery to use Redis running locally as the broker.
Django
# settings.py additions
CELERY_BROKER_URL = 'redis://localhost:6379/0'
Sample Program

This shows how to set up Celery, create a simple task to add two numbers, and run it asynchronously.

Django
# 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()

# tasks.py inside any Django app
from celery import shared_task

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

# Usage in Django shell
# from myapp.tasks import add
# result = add.delay(4, 6)
# print(result.get(timeout=10))
OutputSuccess
Important Notes

Make sure Redis or your chosen broker is running before starting Celery workers.

Run Celery worker with: celery -A your_project worker --loglevel=info

Use delay() to call tasks asynchronously.

Summary

Celery lets Django run tasks in the background to keep the app fast.

Install Celery and a broker like Redis, then configure Celery in your project.

Create tasks with @shared_task and call them with delay().