0
0
Flaskframework~20 mins

After_request hooks in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Using After_request Hooks in Flask
📖 Scenario: You are building a simple Flask web app that returns a greeting message. You want to add a feature that modifies the response before it is sent to the user, such as adding a custom header.
🎯 Goal: Create a Flask app with a route that returns a greeting. Then use an after_request hook to add a custom header X-Custom-Header with the value FlaskProject to every response.
📋 What You'll Learn
Create a Flask app instance named app
Define a route /hello that returns the text Hello, Flask!
Create an after_request function named add_custom_header
In add_custom_header, add the header X-Custom-Header with value FlaskProject to the response
Return the modified response from add_custom_header
💡 Why This Matters
🌍 Real World
After_request hooks are useful to add headers like security policies, CORS, or custom metadata to all responses in a web app.
💼 Career
Understanding Flask hooks is important for backend web development roles that use Python and Flask to build APIs and web services.
Progress0 / 4 steps
1
Create the Flask app and a simple route
Import Flask from flask. Create a Flask app instance called app. Define a route /hello that returns the string 'Hello, Flask!'.
Flask
Need a hint?

Use Flask(__name__) to create the app. Use @app.route('/hello') to define the route.

2
Create the after_request hook function
Define a function called add_custom_header that takes a parameter response. This function will be used as an after_request hook.
Flask
Need a hint?

Define a function with one parameter named response and return it.

3
Add the custom header inside the after_request function
Inside the add_custom_header function, add a header X-Custom-Header with the value FlaskProject to the response.headers. Then return the modified response.
Flask
Need a hint?

Use response.headers['X-Custom-Header'] = 'FlaskProject' to add the header.

4
Register the after_request hook with the Flask app
Register the add_custom_header function as an after_request hook on the app by using the @app.after_request decorator above the function definition.
Flask
Need a hint?

Use @app.after_request decorator above the function add_custom_header.