Complete the code to add middleware that logs each request in Flask.
from flask import Flask, request app = Flask(__name__) @app.before_request def [1](): print(f"Request to: {request.path}") @app.route('/') def home(): return 'Hello!'
The function decorated with @app.before_request runs before each request. Naming it log_request makes its purpose clear.
Complete the code to create middleware that modifies the response headers.
from flask import Flask, Response app = Flask(__name__) @app.after_request def add_header(response: Response): response.headers['X-Custom-Header'] = [1] return response @app.route('/') def home(): return 'Hello!'
The middleware adds a custom header with the value 'Middleware-Active' to the response headers.
Fix the error in the middleware function that blocks requests to '/secret'.
from flask import Flask, request, abort app = Flask(__name__) @app.before_request def block_secret(): if request.path == [1]: abort(403) @app.route('/secret') def secret(): return 'Top secret!'
The path must exactly match '/secret' to block access properly.
Fill both blanks to create middleware that measures request processing time and adds it to response headers.
import time from flask import Flask, g, request app = Flask(__name__) @app.before_request def start_timer(): g.start = [1] @app.after_request def add_duration(response): duration = time.time() - g.start response.headers['X-Duration'] = str(duration) + [2] return response
time.perf_counter() which is more precise but less common hereThe middleware uses time.time() to record the start time and adds the duration in seconds as a string with ' seconds' suffix to the response header.
Fill all three blanks to create middleware that modifies request data and response data.
from flask import Flask, request, jsonify app = Flask(__name__) @app.before_request def modify_request(): if request.is_json: data = request.get_json() data[[1]] = [2] request.json = data @app.after_request def modify_response(response): if response.is_json: json_data = response.get_json() json_data[[3]] = 'modified by middleware' response.set_data(jsonify(json_data).get_data()) return response
The middleware adds a 'middleware_flag' with value True to the request JSON, and adds 'middleware_status' to the response JSON to show it was modified.