Consider this Flask middleware that modifies the response body. What will be the final response content when a client requests the root URL?
from flask import Flask, request, Response app = Flask(__name__) @app.before_request def before(): print('Before request') @app.after_request def after(response): response.set_data(response.get_data(as_text=True) + ' World!') return response @app.route('/') def index(): return 'Hello' if __name__ == '__main__': app.run()
Look at how the after_request function changes the response data.
The after_request middleware appends ' World!' to the original response 'Hello', so the final output is 'Hello World!'.
Given Flask middleware functions before_request and after_request, when are they executed relative to the route handler?
Think about the names and purpose of these middleware hooks.
before_request runs before the route handler to prepare or check the request. after_request runs after the route handler to modify the response.
Choose the correct Flask middleware code that adds the header X-Custom: True to every response.
Remember which middleware hook receives the response object.
The after_request function receives the response object and can modify headers. The before_request does not receive the response.
Examine the middleware code below. What happens when a request is made?
from flask import Flask app = Flask(__name__) @app.before_request def check(): return 'Blocked' @app.route('/') def index(): return 'Hello' if __name__ == '__main__': app.run()
Check what returning a string from before_request does in Flask.
Returning a string from before_request stops further processing and sends that string as the response. This is valid and does not cause an error.
Given these two Flask middleware functions, what is the final response content when requesting '/'?
from flask import Flask, Response app = Flask(__name__) @app.after_request def add_hello(response): response.set_data(response.get_data(as_text=True) + ' Hello') return response @app.after_request def add_world(response): response.set_data(response.get_data(as_text=True) + ' World') return response @app.route('/') def index(): return 'Start' if __name__ == '__main__': app.run()
Consider the order in which multiple after_request functions run (reverse registration order).
Flask runs multiple after_request functions in reverse order of registration. add_world (later registered) runs first, appending ' World', then add_hello appends ' Hello'.