Middleware acts like a checkpoint that can inspect or change requests and responses. It does not replace routing or directly change databases or templates but can add features like logging, authentication, or headers.
from flask import Flask, request app = Flask(__name__) @app.before_request def before(): print('Before request') @app.after_request def after(response): response.headers['X-Custom'] = 'Middleware' return response @app.route('/') def home(): return 'Hello' # Client sends GET /
The after_request function adds a custom header 'X-Custom' with value 'Middleware' to every response before sending it to the client.
Middleware hooks like before_request and after_request run before the route handler and after the response is generated, allowing modification at both stages.
after_request functions must return the response object. Without returning it, Flask sends the original response without the header changes.
Option A correctly adds a new attribute to the request object before the route runs. Option A tries to modify request after response, which is too late. Option A reassigns request, breaking it. Option A tries to modify immutable headers.