Task status monitoring helps you know if a background job is running, done, or failed. It keeps users informed about progress.
Task status monitoring in Flask
Introduction
Syntax
Flask
from flask import Flask, jsonify app = Flask(__name__) tasks = {} @app.route('/start-task') def start_task(): task_id = 'task1' tasks[task_id] = 'running' # simulate task tasks[task_id] = 'completed' return jsonify({'task_id': task_id, 'status': tasks[task_id]}) @app.route('/task-status/<task_id>') def task_status(task_id): status = tasks.get(task_id, 'not found') return jsonify({'task_id': task_id, 'status': status})
Use a dictionary or database to store task statuses.
Define routes to start tasks and check their status.
Examples
Flask
tasks = {}
tasks['task1'] = 'running'
tasks['task1'] = 'completed'Flask
@app.route('/task-status/<task_id>') def task_status(task_id): status = tasks.get(task_id, 'not found') return jsonify({'task_id': task_id, 'status': status})
Sample Program
This Flask app starts a background task that runs for 3 seconds. You can start the task via /start-task and check its status via /task-status/task1.
Flask
from flask import Flask, jsonify import threading import time app = Flask(__name__) tasks = {} def background_task(task_id): tasks[task_id] = 'running' time.sleep(3) # simulate work tasks[task_id] = 'completed' @app.route('/start-task') def start_task(): task_id = 'task1' thread = threading.Thread(target=background_task, args=(task_id,)) thread.start() return jsonify({'task_id': task_id, 'status': 'started'}) @app.route('/task-status/<task_id>') def task_status(task_id): status = tasks.get(task_id, 'not found') return jsonify({'task_id': task_id, 'status': status}) if __name__ == '__main__': app.run(debug=True)
Important Notes
Use threads or background workers to avoid blocking the main Flask app.
Task IDs should be unique if you run multiple tasks.
For production, consider using task queues like Celery for better management.
Summary
Task status monitoring lets users see progress of background jobs.
Store task states in a dictionary or database.
Use Flask routes to start tasks and check their status.
Practice
1. What is the main purpose of task status monitoring in a Flask application?
easy
Solution
Step 1: Understand task status monitoring
Task status monitoring is about showing users how background jobs are progressing.Step 2: Identify the correct purpose
Among the options, only letting users see job progress matches the purpose.Final Answer:
To let users see the progress of background jobs -> Option CQuick Check:
Task status monitoring = show job progress [OK]
Hint: Task status monitoring shows job progress to users [OK]
Common Mistakes:
- Confusing task monitoring with server speed optimization
- Thinking it manages user authentication
- Assuming it restarts the app automatically
2. Which Flask route method is best to check the status of a running background task?
easy
Solution
Step 1: Understand HTTP methods for status checking
GET is used to retrieve information without changing server state.Step 2: Match method to task status check
Checking task status is a read operation, so GET is appropriate.Final Answer:
GET -> Option BQuick Check:
Check status = GET request [OK]
Hint: Use GET to fetch status without changing data [OK]
Common Mistakes:
- Using POST which changes data
- Choosing DELETE which removes data
- Using PUT which updates data
3. Given this Flask code snippet, what will be the output when accessing
/status/task1 if tasks = {'task1': 'running'}?
from flask import Flask, jsonify
app = Flask(__name__)
tasks = {'task1': 'running'}
@app.route('/status/<task_id>')
def status(task_id):
state = tasks.get(task_id, 'not found')
return jsonify({'task': task_id, 'status': state})medium
Solution
Step 1: Check the tasks dictionary for 'task1'
The dictionary has 'task1' with value 'running'.Step 2: Understand the route function output
The function returns JSON with task id and its status from the dictionary.Final Answer:
{"task": "task1", "status": "running"} -> Option AQuick Check:
tasks['task1'] = running [OK]
Hint: Check dictionary key presence for status [OK]
Common Mistakes:
- Assuming missing key returns error instead of default
- Confusing JSON string with Python dict
- Expecting 404 error without explicit handling
4. Identify the error in this Flask route for checking task status:
@app.route('/status/<task_id>')
def status(task_id):
state = tasks[task_id]
return {'task': task_id, 'status': state}medium
Solution
Step 1: Analyze dictionary access
Accessing tasks[task_id] without checking key causes KeyError if missing.Step 2: Confirm other parts are correct
Returning dict is allowed by Flask; decorator and route syntax are correct.Final Answer:
Using tasks[task_id] without checking if key exists -> Option AQuick Check:
Direct dict access risks KeyError [OK]
Hint: Always check dict keys before access to avoid errors [OK]
Common Mistakes:
- Thinking returning dict is wrong in Flask
- Ignoring possible KeyError on missing keys
- Assuming route decorator is missing
5. You want to monitor multiple background tasks in Flask and update their status safely. Which approach is best to store and update task states?
hard
Solution
Step 1: Consider concurrency in Flask background tasks
Multiple tasks may update states concurrently, so thread safety is needed.Step 2: Evaluate storage options
Global dictionary with thread locks ensures safe updates; local vars or files without sync cause errors.Final Answer:
Use a global dictionary with thread locks to store task states -> Option DQuick Check:
Safe shared state needs locks [OK]
Hint: Use locks with shared dict for safe task status updates [OK]
Common Mistakes:
- Using local variables which don't persist
- Ignoring thread safety causing race conditions
- Relying on print statements for monitoring
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
