0
0
Flaskframework~30 mins

Before_request hooks in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Before_request Hooks in Flask
📖 Scenario: You are building a simple Flask web app that needs to check if a user is logged in before allowing access to certain pages.To do this, you will use a before_request hook to run a function before every request. This function will check a variable to decide if the user is logged in.
🎯 Goal: Create a Flask app that uses a before_request hook to check a login status before serving pages.If the user is not logged in, the app should redirect them to a login page.
📋 What You'll Learn
Create a Flask app instance
Define a global variable logged_in set to False
Use @app.before_request to define a function that checks logged_in
Redirect to /login if logged_in is False
Create two routes: / for the home page and /login for the login page
💡 Why This Matters
🌍 Real World
Before_request hooks are used in web apps to run code before every page loads, such as checking if a user is logged in or setting up data.
💼 Career
Understanding before_request hooks is important for backend web developers to control access and prepare requests in Flask applications.
Progress0 / 4 steps
1
Create the Flask app and login status variable
Import Flask and create an app instance called app. Then create a variable called logged_in and set it to False.
Flask
Need a hint?

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

Set logged_in = False as a global variable.

2
Add the before_request hook to check login
Use the @app.before_request decorator to create a function called check_login. Inside it, check if logged_in is False. If so, import and use redirect and request from Flask to redirect to /login unless the current path is already /login.
Flask
Need a hint?

Use @app.before_request above the function.

Inside the function, check if not logged_in and request.path != '/login'.

Return redirect('/login') in that case.

3
Create the home page route
Create a route for / using @app.route('/'). Define a function called home that returns the string 'Welcome to the home page!'.
Flask
Need a hint?

Use @app.route('/') to create the home page route.

Return the welcome string from the home function.

4
Create the login page route
Create a route for /login using @app.route('/login'). Define a function called login that returns the string 'Please log in.'.
Flask
Need a hint?

Use @app.route('/login') to create the login page route.

Return the login prompt string from the login function.