Consider a Flask app with a Celery task defined as follows:
from flask import Flask, jsonify
from celery import Celery
app = Flask(__name__)
celery = Celery(app.name, broker='redis://localhost:6379/0')
@celery.task
def add(x, y):
return x + y
@app.route('/add')
def call_add():
task = add.delay(4, 5)
return jsonify({'task_id': task.id})What will the client receive when accessing the /add route?
from flask import Flask, jsonify from celery import Celery app = Flask(__name__) celery = Celery(app.name, broker='redis://localhost:6379/0') @celery.task def add(x, y): return x + y @app.route('/add') def call_add(): task = add.delay(4, 5) return jsonify({'task_id': task.id})
Remember that delay() queues the task and returns immediately with a task ID.
The delay() method triggers the Celery task asynchronously and returns a task object immediately. The Flask route returns the task ID in JSON format. The actual task runs in the background and its result is not returned directly in this response.
Given a Celery task process_data and calling task = process_data.delay(), what is the initial state of task.state?
from celery import Celery celery = Celery('app', broker='redis://localhost:6379/0') @celery.task def process_data(): return 'done' task = process_data.delay()
Think about what happens right after a task is queued but before it runs.
When a Celery task is first queued with delay(), its state is 'PENDING' because it has not started execution yet.
Choose the correct Flask route code that calls a Celery task asynchronously but waits for the result before returning it.
Look for the method that waits for the task result.
Calling task.get() waits for the Celery task to finish and returns the result. Using delay() queues the task asynchronously, but get() blocks until the result is ready.
Given this Flask route:
@app.route('/longtask')
def longtask():
result = long_running_task.delay()
return result.get()The route hangs and never returns. What is the most likely cause?
@app.route('/longtask') def longtask(): result = long_running_task.delay() return result.get()
Check if the background worker is active.
If the Celery worker process is not running, the task stays queued and result.get() waits forever, causing the Flask route to hang.
Why do developers use Celery to call tasks asynchronously in Flask applications?
Think about what happens when a web server handles slow tasks directly.
Calling tasks asynchronously with Celery allows the Flask app to delegate slow or blocking work to background workers. This keeps the web server responsive and able to handle more requests.