Bird
0
0

Examine the following Flask code snippet:

medium📝 Debug Q6 of 15
Flask - Background Tasks
Examine the following Flask code snippet:
from flask import Flask
import threading
app = Flask(__name__)

@app.route('/start')
def start_task():
    def task():
        print('Task executed')
    threading.Thread(target=task).run()
    return 'Task started'

What is the error in this code?
AMissing <code>app.run()</code> to start the Flask app
BDefining the task function inside the route handler
CUsing <code>run()</code> instead of <code>start()</code> to launch the thread
DNot returning a JSON response from the route
Step-by-Step Solution
Solution:
  1. Step 1: Understand threading methods

    The threading.Thread class has a start() method to begin execution in a new thread. The run() method runs the target function in the current thread synchronously.
  2. Step 2: Identify the error

    The code calls threading.Thread(target=task).run(), which executes task synchronously, blocking the request instead of running it in background.
  3. Final Answer:

    Using run() instead of start() to launch the thread -> Option C
  4. Quick Check:

    Check if start() is used to launch threads [OK]
Quick Trick: Always call start(), not run(), to start a new thread [OK]
Common Mistakes:
MISTAKES
  • Confusing run() with start() in threading
  • Thinking defining functions inside routes is an error
  • Expecting JSON response when plain string is acceptable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes