0
0
Flaskframework~30 mins

Calling tasks asynchronously in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Calling tasks asynchronously in Flask
📖 Scenario: You are building a simple Flask web app that needs to perform a long task without making the user wait. To do this, you will call the task asynchronously.
🎯 Goal: Build a Flask app that starts a background task asynchronously when a user visits a route, so the app stays responsive.
📋 What You'll Learn
Create a Flask app instance
Define a long-running task function
Call the task asynchronously using threading
Create a route that triggers the async task and returns immediately
💡 Why This Matters
🌍 Real World
Web apps often need to perform slow tasks like sending emails or processing files without making users wait. Calling tasks asynchronously keeps the app responsive.
💼 Career
Understanding asynchronous task handling in Flask is important for backend web developers to build efficient and user-friendly web applications.
Progress0 / 4 steps
1
Set up the Flask app and import threading
Import Flask from flask and Thread from threading. Then create a Flask app instance called app.
Flask
Need a hint?

Use from flask import Flask and from threading import Thread. Then create app = Flask(__name__).

2
Define a long-running task function
Define a function called long_task that simulates a long task by importing time and calling time.sleep(5) inside the function.
Flask
Need a hint?

Define def long_task(): and inside it call time.sleep(5) to simulate delay.

3
Call the long task asynchronously
Inside the Flask app, create a route /start-task using @app.route('/start-task'). In the route function called start_task, start long_task asynchronously using Thread(target=long_task).start() and return the string 'Task started' immediately.
Flask
Need a hint?

Use @app.route('/start-task') to define the route. Inside start_task, call Thread(target=long_task).start() and return 'Task started'.

4
Add the app run command
Add the code to run the Flask app by checking if __name__ == '__main__' and calling app.run(debug=True).
Flask
Need a hint?

Add if __name__ == '__main__': and inside it call app.run(debug=True) to start the server.