Bird
Raised Fist0
Flaskframework~10 mins

Task status monitoring in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Task status monitoring
Start Task
↓
Task Running
↓
Check Status Request
↓
Return Current Status
↓
Task Completed?
No→Wait for Next Check
Yes↓
Return Final Status
↓
End
This flow shows how a task starts, runs, and how status requests check and return the current state until completion.
Execution Sample
Flask
from flask import Flask, jsonify
app = Flask(__name__)
tasks = {}

@app.route('/start')
def start_task():
    tasks['task1'] = 'running'
    return jsonify({'status': 'started'})
This code starts a task and sets its status to 'running'.
Execution Table
StepActionTask Status BeforeTask Status AfterResponse Sent
1Start task1{}{'task1': 'running'}{"status": "started"}
2Check status of task1{'task1': 'running'}{'task1': 'running'}{"task1": "running"}
3Update task1 to completed{'task1': 'running'}{'task1': 'completed'}None
4Check status of task1{'task1': 'completed'}{'task1': 'completed'}{"task1": "completed"}
5No more status checks{'task1': 'completed'}{'task1': 'completed'}End monitoring
💡 Task status is 'completed', so monitoring ends.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
tasks{}{'task1': 'running'}{'task1': 'running'}{'task1': 'completed'}{'task1': 'completed'}{'task1': 'completed'}
Key Moments - 2 Insights
Why does the task status not change when we only check it?
Checking the status (Step 2) only reads the current value without modifying it, so the status remains 'running' as shown in the execution_table row 2.
How do we know when to stop monitoring the task?
When the task status becomes 'completed' (Step 4), the monitoring ends as indicated in the exit_note and execution_table row 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the task status after Step 1?
A{}
B'completed'
C'running'
D'started'
💡 Hint
Check the 'Task Status After' column in row 1 of the execution_table.
At which step does the task status change to 'completed'?
AStep 3
BStep 2
CStep 4
DStep 5
💡 Hint
Look at the 'Task Status After' column to see when 'completed' first appears.
If we never update the task status to 'completed', what happens in the monitoring?
ATask status becomes 'failed'
BMonitoring continues indefinitely
CMonitoring ends immediately
DTask is removed from tasks dictionary
💡 Hint
Refer to the concept_flow where monitoring loops until status is 'completed'.
Concept Snapshot
Task status monitoring in Flask:
- Start task and set status (e.g., 'running')
- Provide endpoint to check current status
- Update status when task completes
- Continue checking until status is 'completed'
- Use a dictionary to track task states
- Return JSON responses with current status
Full Transcript
This example shows how to monitor a task's status in Flask. We start a task by setting its status to 'running' in a dictionary. When a client requests the status, the server returns the current state without changing it. Later, the task status is updated to 'completed'. The monitoring continues until the status is 'completed', at which point it stops. This process uses simple Flask routes and a dictionary to track task states, returning JSON responses to clients.

Practice

(1/5)
1. What is the main purpose of task status monitoring in a Flask application?
easy
A. To store user login credentials securely
B. To speed up the Flask server response time
C. To let users see the progress of background jobs
D. To automatically restart the Flask app on errors

Solution

  1. Step 1: Understand task status monitoring

    Task status monitoring is about showing users how background jobs are progressing.
  2. Step 2: Identify the correct purpose

    Among the options, only letting users see job progress matches the purpose.
  3. Final Answer:

    To let users see the progress of background jobs -> Option C
  4. Quick 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
A. POST
B. GET
C. DELETE
D. PUT

Solution

  1. Step 1: Understand HTTP methods for status checking

    GET is used to retrieve information without changing server state.
  2. Step 2: Match method to task status check

    Checking task status is a read operation, so GET is appropriate.
  3. Final Answer:

    GET -> Option B
  4. Quick 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
A. {"task": "task1", "status": "running"}
B. {"task": "task1", "status": "not found"}
C. 404 Not Found error
D. SyntaxError

Solution

  1. Step 1: Check the tasks dictionary for 'task1'

    The dictionary has 'task1' with value 'running'.
  2. Step 2: Understand the route function output

    The function returns JSON with task id and its status from the dictionary.
  3. Final Answer:

    {"task": "task1", "status": "running"} -> Option A
  4. Quick 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
A. Using tasks[task_id] without checking if key exists
B. Returning a dictionary instead of JSON response
C. Missing @app.route decorator
D. Incorrect route URL syntax

Solution

  1. Step 1: Analyze dictionary access

    Accessing tasks[task_id] without checking key causes KeyError if missing.
  2. Step 2: Confirm other parts are correct

    Returning dict is allowed by Flask; decorator and route syntax are correct.
  3. Final Answer:

    Using tasks[task_id] without checking if key exists -> Option A
  4. Quick 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
A. Store task states only in local variables inside routes
B. Store task states in a file without synchronization
C. Use print statements to track task progress in console
D. Use a global dictionary with thread locks to store task states

Solution

  1. Step 1: Consider concurrency in Flask background tasks

    Multiple tasks may update states concurrently, so thread safety is needed.
  2. Step 2: Evaluate storage options

    Global dictionary with thread locks ensures safe updates; local vars or files without sync cause errors.
  3. Final Answer:

    Use a global dictionary with thread locks to store task states -> Option D
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard