0
0
Djangoframework~5 mins

Calling tasks asynchronously in Django

Choose your learning style9 modes available
Introduction

Calling tasks asynchronously lets your app do work in the background. This keeps the app fast and responsive for users.

Sending emails without making the user wait
Processing uploaded files after user submits a form
Running long calculations without freezing the website
Updating data from external sources regularly without slowing down the app
Syntax
Django
from celery import shared_task

@shared_task
def my_task(*args):
    # task code here

# To call the task asynchronously:
my_task.delay(*args)

Use @shared_task decorator to define a task.

Call the task with .delay() to run it in the background.

Examples
This example shows a task to send a welcome email to a user by their ID.
Django
from celery import shared_task

@shared_task
def send_welcome_email(user_id):
    # code to send email
    pass

# Call asynchronously
send_welcome_email.delay(42)
This task adds two numbers. Calling with .delay() runs it in the background.
Django
from celery import shared_task

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

# Call asynchronously
result = add_numbers.delay(3, 5)
Sample Program

This program defines a task to multiply two numbers. It calls the task asynchronously and prints the task ID.

Django
from celery import shared_task

@shared_task
def multiply(x, y):
    return x * y

# Calling the task asynchronously
result = multiply.delay(4, 7)

print(f"Task called asynchronously. Task ID: {result.id}")
OutputSuccess
Important Notes

You need to have Celery and a message broker like Redis or RabbitMQ set up to run tasks asynchronously.

The .delay() method immediately returns a task object with an ID, not the task result.

To get the result later, you can use result.get() but this blocks until the task finishes.

Summary

Use Celery tasks to run code in the background.

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

This helps keep your Django app fast and responsive.