📖 Scenario: You are building a simple web app where users can log in and see a welcome page. To manage user sessions easily, you will use the Flask-Login extension.
🎯 Goal: Create a Flask app that uses Flask-Login to handle user login, logout, and session management with a single test user.
📋 What You'll Learn
Create a Flask app instance
Set up Flask-Login with a user loader
Create a User class compatible with Flask-Login
Implement login and logout routes
Protect a route so only logged-in users can access it
💡 Why This Matters
🌍 Real World
User login systems are essential for websites and apps to control access and personalize content.
💼 Career
Understanding Flask-Login helps backend developers build secure user authentication in Python web apps.
Progress0 / 4 steps
1
Set up Flask app and User class
Import Flask from flask and LoginManager, UserMixin from flask_login. Create a Flask app called app. Define a User class that inherits from UserMixin and has an id attribute set to 1.
Flask
Hint
Start by importing Flask and LoginManager. Then create the app and a simple User class with an id.
2
Configure Flask-Login and user loader
Create a LoginManager instance called login_manager and initialize it with app. Define a function load_user that takes user_id and returns a User instance if user_id is '1', else returns None. Register this function with login_manager.user_loader.
Flask
Hint
Initialize LoginManager with your app and create a user loader function that returns the User instance for id '1'.
3
Add login and logout routes
Import login_user, logout_user, and login_required from flask_login. Create a route /login that logs in the User instance and returns the text 'Logged in!'. Create a route /logout that logs out the user and returns 'Logged out!'.
Flask
Hint
Create routes for login and logout that call the right Flask-Login functions and return simple text.
4
Protect a route with login_required
Create a route /profile that is protected with @login_required. This route should return the text 'Welcome to your profile!'. Also, set app.secret_key to 'secret123' to enable session management.
Flask
Hint
Set a secret key for sessions and protect the profile route with @login_required decorator.
Practice
(1/5)
1. What is the main purpose of the Flask-Login extension in a Flask application?
easy
A. To create database models for users
B. To manage user sessions and handle login/logout functionality
C. To style the login page with CSS
D. To send emails to users after login
Solution
Step 1: Understand Flask-Login's role
Flask-Login is designed to manage user sessions, making it easy to log users in and out securely.
Step 2: Compare options with Flask-Login's purpose
Creating database models, styling pages, or sending emails are not handled by Flask-Login.
Final Answer:
To manage user sessions and handle login/logout functionality -> Option B
Quick Check:
Flask-Login manages user sessions = A [OK]
Hint: Remember: Flask-Login handles login sessions, not styling or emails [OK]
Common Mistakes:
Confusing Flask-Login with database or styling tools
Thinking Flask-Login sends emails
Assuming it creates user database models
2. Which of the following is the correct way to initialize Flask-Login's LoginManager in a Flask app using an application factory pattern?
easy
A. login_manager = LoginManager(); login_manager.init_app(app)
B. login_manager = LoginManager(app=app)
C. login_manager = LoginManager(app)
D. login_manager = LoginManager.init_app(app)
Solution
Step 1: Recall Flask-Login initialization pattern
The usual pattern is to create a LoginManager instance without arguments, then call init_app(app) to bind it.
Step 2: Check each option's syntax
login_manager = LoginManager(); login_manager.init_app(app) correctly creates the instance and calls init_app(app). login_manager = LoginManager(app) tries to pass app to constructor which is not standard. login_manager = LoginManager(app=app) uses a wrong keyword argument. login_manager = LoginManager.init_app(app) calls init_app as a class method, which is invalid.
Final Answer:
login_manager = LoginManager(); login_manager.init_app(app) -> Option A
Quick Check:
Use init_app() after creating LoginManager = C [OK]
Hint: Create LoginManager first, then call init_app(app) [OK]
Common Mistakes:
Passing app directly to LoginManager constructor
Using wrong argument names
Calling init_app as a class method
3. Given this Flask-Login user loader function, what will load_user('42') return if the user with ID 42 exists in the database?
A. User.get(user_id) should be User.query.get(user_id)
B. login_manager.init_app(app) must be called before defining load_user
C. user_loader decorator is missing parentheses
D. login_manager must be created after app
Solution
Step 1: Check user_loader function correctness
The typical way to get a user by ID in Flask-SQLAlchemy is User.query.get(user_id). Using User.get(user_id) will cause an AttributeError.
Step 2: Verify other parts of the code
Calling init_app(app) after defining user_loader is fine. The decorator syntax is correct. Creating LoginManager before app is allowed if init_app is called later.
Final Answer:
User.get(user_id) should be User.query.get(user_id) -> Option A
Quick Check:
User.get() is invalid, use User.query.get() = B [OK]
Hint: Use User.query.get() to fetch user by ID [OK]
Common Mistakes:
Using User.get() instead of User.query.get()
Thinking init_app must be called before user_loader
Misunderstanding decorator syntax
5. You want to protect a Flask route so only logged-in users can access it. Which is the correct way to do this using Flask-Login?
hard
A. Manually check session variables for user login status
B. Check if current_user.is_authenticated inside the route and redirect if not
C. Use the @login_required decorator on the route function
D. Add login_manager.login_view = 'login' inside the route function
Flask-Login provides a @login_required decorator to easily protect routes so only logged-in users can access them.
Step 2: Evaluate other options
Check if current_user.is_authenticated inside the route and redirect if not is possible but less clean and requires manual redirect logic. Manually check session variables for user login status is low-level and error-prone. Add login_manager.login_view = 'login' inside the route function sets the login page globally but does not protect routes by itself.
Final Answer:
Use the @login_required decorator on the route function -> Option C
Quick Check:
Use @login_required to protect routes = A [OK]
Hint: Use @login_required decorator for easy route protection [OK]
Common Mistakes:
Manually checking login status instead of using decorator
Confusing login_view setting with route protection
Ignoring Flask-Login's built-in decorators
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.