Performance: Defining tasks
This affects how background work impacts server responsiveness and page load times.
Jump into concepts and practice - no test required
from celery import shared_task @shared_task def long_task(): # Long running code here pass def view(request): long_task.delay() return HttpResponse('Task started')
def view(request): # Long task runs synchronously result = long_task() return HttpResponse(result)
| Pattern | Server Blocking | Response Delay | User Interaction Impact | Verdict |
|---|---|---|---|---|
| Synchronous task in view | Blocks server thread | Delays response by task duration | High input delay (INP) | [X] Bad |
| Asynchronous task with Celery | No blocking | Immediate response | Low input delay (INP) | [OK] Good |
@shared_task decorator to mark functions as tasks that can run asynchronously.@shared_task is the correct and standard decorator for defining tasks.delay() method on the task function.delay() triggers the task asynchronously; other methods like run() execute synchronously or do not exist.from celery import shared_task
@shared_task
def add(x, y):
return x + y
result = add.delay(4, 5)result.get() return?add function adds two numbers. Calling add.delay(4, 5) runs it asynchronously and returns an AsyncResult.result.get() retrieves the task resultresult.get() waits for the task to finish and returns the sum, which is 9.from celery import shared_task @shared_task def multiply(x, y): return x * y
return x * y is not indented.@shared_task and checks if email: which correctly tests for a non-empty email.