Consider a Flask route that processes a long task directly in the request handler. What is the user experience during this time?
from flask import Flask import time app = Flask(__name__) @app.route('/long-task') def long_task(): time.sleep(10) # Simulates a long task return 'Task complete!'
Think about what happens when the server is busy doing one thing.
When a Flask route runs a long task synchronously, the server holds the connection open and the user waits until the task finishes. No response is sent during the wait.
Given a Flask app using Celery to run a background task, what will the user see immediately after triggering the task?
from flask import Flask, jsonify from celery import Celery app = Flask(__name__) app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0' celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) @celery.task def background_task(): import time time.sleep(5) return 'Done' @app.route('/start-task') def start_task(): task = background_task.delay() return jsonify({'task_id': task.id, 'status': 'started'})
Background tasks let the server respond immediately.
The Flask route triggers the background task and immediately returns a JSON response with the task ID and status. The long task runs separately.
Examine the Flask app below. Why does it freeze or become unresponsive when multiple users access the /process route simultaneously?
from flask import Flask import time app = Flask(__name__) @app.route('/process') def process(): time.sleep(10) # Simulate long processing return 'Done' if __name__ == '__main__': app.run()
Think about how Flask's built-in server handles requests.
Flask's built-in development server is single-threaded by default, so it processes one request at a time. Long tasks block other requests, causing freezing.
Which of the following is the best reason to use background processing in a Flask web app?
Think about what users feel when waiting for slow tasks.
Background processing lets the app handle long tasks separately, so users get quick responses and the server stays responsive.
Choose the code that correctly starts a background task in Flask using Python's threading module without blocking the main request.
from flask import Flask import threading import time app = Flask(__name__) def background_task(): time.sleep(5) print('Background task done') @app.route('/start') def start(): # Which option correctly starts the background task? pass
Remember how to create and start a thread properly.
Option C correctly creates a Thread object with the target function and starts it. Option C runs the task synchronously. Option C calls the function immediately and passes its result (None) to Thread. Option C uses a deprecated function incorrectly.