0
0
Flaskframework~30 mins

Before_request as middleware alternative in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Using before_request as Middleware Alternative in Flask
📖 Scenario: You are building a simple Flask web app that needs to check if a user is authenticated before allowing access to certain pages.Instead of writing the authentication check inside every route, you want to use Flask's before_request function as a middleware alternative to run this check automatically before each request.
🎯 Goal: Create a Flask app that uses before_request to check if a user is logged in before accessing the /dashboard route. If the user is not logged in, redirect them to the /login page.
📋 What You'll Learn
Create a Flask app instance named app
Define a global variable logged_in set to False initially
Use @app.before_request to create a function named check_login that checks if the user is logged in
If the user is not logged in and tries to access /dashboard, redirect to /login
Create two routes: /login and /dashboard that return simple text responses
💡 Why This Matters
🌍 Real World
Web apps often need to check user authentication before allowing access to certain pages. Using before_request as middleware helps keep the code clean and centralized.
💼 Career
Understanding middleware patterns and request lifecycle in Flask is essential for backend web development roles.
Progress0 / 4 steps
1
Set up Flask app and login status
Import Flask and redirect from flask. Create a Flask app instance called app. Create a global variable called logged_in and set it to False.
Flask
Need a hint?

Use app = Flask(__name__) to create the app instance.

Set logged_in = False to represent the user not logged in yet.

2
Add before_request function to check login
Use the @app.before_request decorator to create a function named check_login. Inside it, check if logged_in is False and if the requested path is /dashboard. If both are true, return a redirect to /login.
Flask
Need a hint?

Use @app.before_request to run check_login before every request.

Use request.path to get the current URL path.

3
Create /login and /dashboard routes
Create a route /login that returns the text 'Please log in.'. Create another route /dashboard that returns the text 'Welcome to your dashboard.'.
Flask
Need a hint?

Use @app.route('/login') and @app.route('/dashboard') to define routes.

Return simple strings from each route function.

4
Add app run block for local testing
Add the standard Flask app run block: if __name__ == '__main__': and inside it call app.run(debug=True).
Flask
Need a hint?

This block allows you to run the Flask app locally for testing.