Task results and status help you know if a background job finished, is still running, or failed. This keeps your app responsive and organized.
Task results and status in Django
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Django
from celery.result import AsyncResult result = AsyncResult(task_id) status = result.status output = result.result
AsyncResult lets you check a task by its ID.
status can be PENDING, STARTED, SUCCESS, FAILURE, etc.
Examples
Django
result = AsyncResult('some-task-id') print(result.status)
Django
if result.successful(): print('Task done! Result:', result.result)
Django
if result.failed(): print('Task failed. Reason:', result.result)
Sample Program
This example creates a simple task to add two numbers. It starts the task, checks its status, waits for it to finish, then prints the final status and result.
Django
from celery import Celery from celery.result import AsyncResult app = Celery('tasks', broker='redis://localhost:6379/0') @app.task def add(x, y): return x + y # Start a task async_result = add.delay(4, 6) # Check status and result result = AsyncResult(async_result.id) print('Status:', result.status) # Wait for task to finish (in real app, you check later) result.get(timeout=10) print('Final Status:', result.status) print('Result:', result.result)
Important Notes
Task status updates as the task runs or finishes.
Use result.get() carefully; it waits for the task to finish and can block your app.
Store task IDs if you want to check results later.
Summary
Use AsyncResult to check task status and results by task ID.
Status shows if a task is pending, running, succeeded, or failed.
Task results help you respond to users or handle errors after background work.
Practice
1. In Django with Celery, which object do you use to check the status and result of a background task by its ID?
easy
Solution
Step 1: Identify the object for task tracking
Celery providesAsyncResultto track task status and results using the task ID.Step 2: Confirm usage in Django context
In Django projects using Celery,AsyncResultis the standard way to check if a task is pending, running, or finished.Final Answer:
AsyncResult -> Option AQuick Check:
Task status and results = AsyncResult [OK]
Hint: Remember: AsyncResult tracks task status by ID [OK]
Common Mistakes:
- Confusing AsyncResult with task function names
- Using non-existent classes like TaskStatus
- Trying to access results directly without AsyncResult
2. Which of the following is the correct way to create an
AsyncResult instance for a task with ID stored in task_id?easy
Solution
Step 1: Recall AsyncResult constructor usage
TheAsyncResultclass is instantiated by passing the task ID as the first argument.Step 2: Check each option's syntax
OnlyAsyncResult(task_id)correctly creates the instance. Methods like.get()or.fetch()are not constructors.Final Answer:
result = AsyncResult(task_id) -> Option DQuick Check:
Instantiate AsyncResult with task ID directly [OK]
Hint: Use AsyncResult(task_id) to create result object [OK]
Common Mistakes:
- Calling get() or fetch() as constructor
- Passing keyword argument 'task' instead of positional
- Confusing AsyncResult with task function calls
3. Given the code:
What will
result = AsyncResult('abc123')
status = result.status
output = result.resultWhat will
status and output represent if the task is still running?medium
Solution
Step 1: Understand AsyncResult status values
By default, while a task is running without calling update_state inside the task,result.statusremains 'PENDING'.Step 2: Check result property during running
result.resultreturnsNoneuntil the task completes.Final Answer:
status is 'PENDING', output is None -> Option AQuick Check:
Running task (default): status='PENDING', result=None [OK]
Hint: Default running tasks show status 'PENDING' and result None [OK]
Common Mistakes:
- Mistaking for 'RUNNING' status (doesn't exist)
- Confusing with 'STARTED' which requires explicit update_state
- Thinking result is available before completion
4. You wrote:
But it always prints 'Task not done' even after task completion. What is the likely issue?
result = AsyncResult(task_id)
if result.status == 'SUCCESS':
print(result.result)
else:
print('Task not done')But it always prints 'Task not done' even after task completion. What is the likely issue?
medium
Solution
Step 1: Understand status checking logic
The code checks ifresult.statusequals 'SUCCESS' to print the result.Step 2: Identify why status never shows 'SUCCESS'
If the task ID is wrong or expired,AsyncResultwill not find the task and status stays 'PENDING' or similar.Final Answer:
The task ID is incorrect or expired -> Option CQuick Check:
Wrong task ID causes status never to be 'SUCCESS' [OK]
Hint: Check task ID validity if status never changes [OK]
Common Mistakes:
- Using wrong status string like 'COMPLETED'
- Assuming result.result always updates without completion
- Ignoring task ID correctness
5. You want to handle a task result in Django only if it succeeded, otherwise log the error. Which code snippet correctly checks the task status and safely accesses the result or error?
hard
Solution
Step 1: Understand safe result retrieval
Usingresult.get()with a timeout waits for completion and raises exceptions on failure.Step 2: Check error handling approach
Wrappingresult.get()in try-except catches task failures and allows logging errors safely.Step 3: Compare other options
Options B, C, and D do not handle exceptions properly; C incorrectly treats 'PENDING' as success.Final Answer:
Use try-except with result.get() to handle success and failure -> Option BQuick Check:
Use result.get() with try-except for safe task result handling [OK]
Hint: Use try-except with result.get() to catch errors [OK]
Common Mistakes:
- Checking only status strings without exception handling
- Assuming ready() means success
- Treating PENDING as success
