0
0
Djangoframework~30 mins

Calling tasks asynchronously in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Calling tasks asynchronously in Django
📖 Scenario: You are building a Django web app that sends welcome emails to new users. To avoid slowing down the user signup process, you want to send these emails asynchronously in the background.
🎯 Goal: Learn how to call a task asynchronously in Django using Celery. You will create a simple task to send a welcome email and then call it asynchronously from a Django view.
📋 What You'll Learn
Create a Celery task function called send_welcome_email in tasks.py
Create a Django view function called signup that calls send_welcome_email asynchronously
Use the delay() method to call the task asynchronously
Ensure the task function accepts a user_email parameter
💡 Why This Matters
🌍 Real World
Many web apps need to perform slow tasks like sending emails or processing files without making users wait. Calling tasks asynchronously with Celery is a common solution.
💼 Career
Understanding how to run background tasks asynchronously is important for backend developers working with Django and Celery in real-world projects.
Progress0 / 4 steps
1
Create the Celery task function
Create a file called tasks.py and define a Celery task function named send_welcome_email that accepts a parameter user_email. Inside the function, add a comment # Code to send email to represent the email sending logic.
Django
Need a hint?

Use the @shared_task decorator to define a Celery task function.

2
Create the signup view function
In your Django app's views.py, create a function called signup that accepts a request parameter. Inside the function, create a variable user_email and set it to the string 'newuser@example.com'.
Django
Need a hint?

Define a simple view function with the exact name signup and set user_email to the given email string.

3
Call the task asynchronously
Inside the signup function, call the send_welcome_email task asynchronously using the delay() method and pass user_email as the argument.
Django
Need a hint?

Use the delay() method on the task function to call it asynchronously.

4
Complete the signup view
Add a return statement in the signup function that returns a simple HTTP response with the text 'Signup successful' using Django's HttpResponse.
Django
Need a hint?

Import HttpResponse and return it with the exact text.