Bird
0
0

You want to run a long task asynchronously in Flask and update a database after it finishes. Which approach correctly ensures Flask app context is available in the background task?

hard📝 Application Q15 of 15
Flask - Background Tasks
You want to run a long task asynchronously in Flask and update a database after it finishes. Which approach correctly ensures Flask app context is available in the background task?
AUse <code>with app.app_context():</code> inside the background task function.
BCall the background task directly inside the route without threading.
CStart the thread without any context handling; Flask shares context automatically.
DUse <code>app.run()</code> inside the background task to get context.
Step-by-Step Solution
Solution:
  1. Step 1: Recall Flask app context rules

    Background tasks need explicit app context to access Flask features like database.
  2. Step 2: Identify correct context usage

    Using with app.app_context(): inside the task ensures context is active during task execution.
  3. Step 3: Eliminate incorrect options

    Calling task directly blocks request; Flask does not share context automatically; app.run() starts server, not context.
  4. Final Answer:

    Use with app.app_context(): inside the background task function. -> Option A
  5. Quick Check:

    Use app.app_context() in thread = B [OK]
Quick Trick: Wrap background code with app.app_context() to access Flask features [OK]
Common Mistakes:
MISTAKES
  • Running task directly blocking the app
  • Assuming Flask shares context automatically
  • Misusing app.run() inside tasks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes