Bird
0
0

Identify the error in this Flask code snippet for running a background task:

medium📝 Debug Q6 of 15
Flask - Background Tasks
Identify the error in this Flask code snippet for running a background task:
from threading import Thread

def background_task():
    print('Running')

@app.route('/')
def index():
    Thread(target=background_task()).start()
    return 'Done'
AThread class cannot be used in Flask apps.
BThe target argument should be the function name without parentheses.
CThe print statement is invalid inside threads.
DThe route function must return None.
Step-by-Step Solution
Solution:
  1. Step 1: Check Thread target usage

    Thread target expects a function reference, not a function call.
  2. Step 2: Identify the mistake

    Using background_task() calls the function immediately, passing its result instead of the function.
  3. Final Answer:

    The target argument should be the function name without parentheses. -> Option B
  4. Quick Check:

    Thread target = function name, no parentheses [OK]
Quick Trick: Pass function name to Thread target, no parentheses [OK]
Common Mistakes:
MISTAKES
  • Calling function instead of passing reference
  • Thinking Thread can't be used in Flask
  • Believing print is invalid in threads

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes