Bird
0
0

What is wrong with this Flask code that tries to run a background task?

medium📝 Debug Q14 of 15
Flask - Background Tasks
What is wrong with this Flask code that tries to run a background task?
from threading import Thread
from flask import Flask
app = Flask(__name__)
def task():
    print(app.name)
@app.route('/')
def index():
    Thread(target=task).start()
    return 'Done'
ARoute function must return JSON, not string.
BThe background thread lacks Flask app context, causing errors.
CFlask app cannot print its name inside a thread.
DThread target function must be called with parentheses.
Step-by-Step Solution
Solution:
  1. Step 1: Identify Flask app context issue

    Background threads don't have Flask app context by default, so accessing app.name can fail.
  2. Step 2: Understand context handling

    To fix, use app.app_context() inside the thread to provide context.
  3. Final Answer:

    The background thread lacks Flask app context, causing errors. -> Option B
  4. Quick Check:

    Missing app context in thread = D [OK]
Quick Trick: Background threads need app context to access Flask variables [OK]
Common Mistakes:
MISTAKES
  • Calling target function instead of passing it
  • Thinking Flask disallows printing app.name
  • Believing route must return JSON always

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes