📖 Scenario: You are building a simple Flask web app that needs to perform a long task without making the user wait. To do this, you will call the task asynchronously.
🎯 Goal: Build a Flask app that starts a background task asynchronously when a user visits a route, so the app stays responsive.
📋 What You'll Learn
Create a Flask app instance
Define a long-running task function
Call the task asynchronously using threading
Create a route that triggers the async task and returns immediately
💡 Why This Matters
🌍 Real World
Web apps often need to perform slow tasks like sending emails or processing files without making users wait. Calling tasks asynchronously keeps the app responsive.
💼 Career
Understanding asynchronous task handling in Flask is important for backend web developers to build efficient and user-friendly web applications.
Progress0 / 4 steps
1
Set up the Flask app and import threading
Import Flask from flask and Thread from threading. Then create a Flask app instance called app.
Flask
Hint
Use from flask import Flask and from threading import Thread. Then create app = Flask(__name__).
2
Define a long-running task function
Define a function called long_task that simulates a long task by importing time and calling time.sleep(5) inside the function.
Flask
Hint
Define def long_task(): and inside it call time.sleep(5) to simulate delay.
3
Call the long task asynchronously
Inside the Flask app, create a route /start-task using @app.route('/start-task'). In the route function called start_task, start long_task asynchronously using Thread(target=long_task).start() and return the string 'Task started' immediately.
Flask
Hint
Use @app.route('/start-task') to define the route. Inside start_task, call Thread(target=long_task).start() and return 'Task started'.
4
Add the app run command
Add the code to run the Flask app by checking if __name__ == '__main__' and calling app.run(debug=True).
Flask
Hint
Add if __name__ == '__main__': and inside it call app.run(debug=True) to start the server.
Practice
(1/5)
1. What is the main benefit of calling tasks asynchronously in a Flask app?
easy
A. It forces users to refresh the page manually.
B. It makes the app run slower by adding extra steps.
C. It disables other parts of the app until the task finishes.
D. It allows the app to handle long tasks without making users wait.
Solution
Step 1: Understand asynchronous task purpose
Asynchronous tasks let the app do long jobs in the background.
Step 2: Connect to user experience
This means users don't have to wait for the task to finish before using the app.
Final Answer:
It allows the app to handle long tasks without making users wait. -> Option D
Quick Check:
Async tasks improve user wait time = C [OK]
Hint: Async tasks run in background, so users don't wait [OK]
Common Mistakes:
Thinking async tasks slow down the app
Believing users must refresh manually
Assuming async disables other app parts
2. Which of the following is the correct way to start a background thread in Flask?
easy
A. start_thread(task)
B. thread.start(task())
C. threading.Thread(target=task).start()
D. Thread.run(task)
Solution
Step 1: Recall Python threading syntax
To start a thread, create Thread with target function, then call start().
A. Hello printed immediately, then 'Task done' printed later
B. Only 'Hello' is printed, 'Task done' never prints
C. Both 'Hello' and 'Task done' print at the same time
D. SyntaxError because Thread is used incorrectly
Solution
Step 1: Understand thread behavior in Flask route
The route starts a thread to run background_task, then returns 'Hello' immediately.
Step 2: Predict output order
'Hello' is sent to user right away; 'Task done' prints later when thread runs.
Final Answer:
Hello printed immediately, then 'Task done' printed later -> Option A
Quick Check:
Thread runs task after response = A [OK]
Hint: Thread runs task after response, so print order differs [OK]
Common Mistakes:
Thinking 'Task done' prints before 'Hello'
Assuming thread blocks response
Believing thread syntax is wrong here
4. 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'
medium
A. Route function must return JSON, not string.
B. The background thread lacks Flask app context, causing errors.
C. Flask app cannot print its name inside a thread.
D. Thread target function must be called with parentheses.
Solution
Step 1: Identify Flask app context issue
Background threads don't have Flask app context by default, so accessing app.name can fail.
Step 2: Understand context handling
To fix, use app.app_context() inside the thread to provide context.
Final Answer:
The background thread lacks Flask app context, causing errors. -> Option B
Quick Check:
Missing app context in thread = D [OK]
Hint: Background threads need app context to access Flask variables [OK]
Common Mistakes:
Calling target function instead of passing it
Thinking Flask disallows printing app.name
Believing route must return JSON always
5. 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
A. Use with app.app_context(): inside the background task function.
B. Call the background task directly inside the route without threading.
C. Start the thread without any context handling; Flask shares context automatically.
D. Use app.run() inside the background task to get context.
Solution
Step 1: Recall Flask app context rules
Background tasks need explicit app context to access Flask features like database.
Step 2: Identify correct context usage
Using with app.app_context(): inside the task ensures context is active during task execution.
Step 3: Eliminate incorrect options
Calling task directly blocks request; Flask does not share context automatically; app.run() starts server, not context.
Final Answer:
Use with app.app_context(): inside the background task function. -> Option A
Quick Check:
Use app.app_context() in thread = B [OK]
Hint: Wrap background code with app.app_context() to access Flask features [OK]
Common Mistakes:
Running task directly blocking the app
Assuming Flask shares context automatically
Misusing app.run() inside tasks
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.