0
0
Flaskframework~30 mins

Defining Celery tasks in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Defining Celery Tasks in Flask
📖 Scenario: You are building a Flask web application that needs to perform background tasks without blocking the main app. You will use Celery to define and run these tasks asynchronously.
🎯 Goal: Create a Celery task in a Flask app that adds two numbers and returns the result.
📋 What You'll Learn
Create a Celery instance linked to the Flask app
Define a simple Celery task function
Use the Celery task decorator correctly
Ensure the task can be called asynchronously
💡 Why This Matters
🌍 Real World
Background tasks like sending emails, processing images, or running long computations without blocking the web server.
💼 Career
Many web developer roles require knowledge of asynchronous task queues like Celery to build scalable and responsive applications.
Progress0 / 4 steps
1
Set up Flask app and Celery instance
Create a Flask app instance called app and a Celery instance called celery linked to app with the broker URL set to redis://localhost:6379/0.
Flask
Need a hint?

Use Flask(__name__) to create the app and pass app.name and broker URL to Celery.

2
Configure Celery task decorator
Add a Celery task decorator to a function called add that takes two parameters x and y.
Flask
Need a hint?

Use @celery.task above the function definition to make it a Celery task.

3
Call the Celery task asynchronously
Call the add task asynchronously using the delay method with arguments 4 and 6, and assign the result to a variable called result.
Flask
Need a hint?

Use add.delay(4, 6) to call the task asynchronously and assign it to result.

4
Complete the Flask app with a route to trigger the task
Add a Flask route /start-task that triggers the add task asynchronously with 10 and 20, and returns a string with the task id using result.id.
Flask
Need a hint?

Use @app.route('/start-task') to define the route and call add.delay(10, 20) inside the function.