Performance: Defining Celery tasks
This affects the responsiveness of the Flask web app by offloading long-running tasks to background workers, improving user interaction speed.
from flask import Flask from celery import Celery app = Flask(__name__) celery = Celery('tasks', broker='redis://localhost:6379/0') @celery.task def long_running_task(): # Long task code here return 'done' @app.route('/process') def process(): task = long_running_task.delay() return f"Task started: {task.id}"
from flask import Flask app = Flask(__name__) @app.route('/process') def process(): # Long task runs here result = long_running_task() return f"Result: {result}"
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous task in Flask route | Minimal | 0 | 0 | [X] Bad |
| Asynchronous Celery task with immediate response | Minimal | 0 | 0 | [OK] Good |
@celery_app.task?@celery_app.task decorator marks a function to run as a background task outside the main Flask process.@celery_app.task.@celery_app.task above the function definition.add.delay(4, 5) is called?
from celery import Celery
celery_app = Celery('tasks')
@celery_app.task
def add(x, y):
return x + y
result = add.delay(4, 5)
print(type(result))delay() method queues the task and returns an AsyncResult object, not the actual result.type(result) shows the class of the returned object, which is celery.result.AsyncResult.from celery import Celery
celery_app = Celery('tasks')
@celery_app.task()
def multiply(x, y):
return x * y
result = multiply.delay(3, 7)
print(result.get())@celery_app.task() is allowed and works correctly.delay() queues the task, and result.get() waits for and returns the result properly.if not email: return to exit early, preventing sending to empty emails.if not email: return to skip empty input [OK]Pass the test and this pattern moves unknown