Bird
Raised Fist0
Flaskframework~20 mins

Flask-Login extension - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flask-Login Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a user accesses a @login_required route without being logged in?
Consider a Flask app using Flask-Login with a route decorated by @login_required. What is the behavior when an anonymous user tries to access this route?
Flask
from flask import Flask
from flask_login import LoginManager, login_required

app = Flask(__name__)
login_manager = LoginManager(app)

@login_manager.unauthorized_handler
def unauthorized():
    return 'Redirected to login', 302

@app.route('/dashboard')
@login_required
def dashboard():
    return 'Welcome to your dashboard!'
AThe user is redirected to the login page or unauthorized handler is called.
BThe server crashes with an exception.
CThe server returns a 404 Not Found error.
DThe user sees the dashboard content without logging in.
Attempts:
2 left
💡 Hint
Think about what @login_required does when the user is not authenticated.
❓ state_output
intermediate
1:30remaining
What is the value of current_user.is_authenticated after login?
After a user successfully logs in using Flask-Login's login_user(user) function, what is the value of current_user.is_authenticated?
Flask
from flask_login import current_user, login_user

# Assume user is a valid User object
login_user(user)

value = current_user.is_authenticated
ATrue
BFalse
CNone
DRaises an AttributeError
Attempts:
2 left
💡 Hint
Check what current_user.is_authenticated means after login.
📝 Syntax
advanced
2:30remaining
Which code snippet correctly sets up user_loader for Flask-Login?
You want to tell Flask-Login how to load a user from a user ID stored in the session. Which snippet correctly implements the user_loader callback?
A
@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)
B
@login_manager.user_loader
def load_user(user_id):
    return User.load(user_id)
C
@login_manager.user_loader
def load_user(user_id):
    return User.find_by_id(user_id)
D
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
Attempts:
2 left
💡 Hint
Flask-Login expects a function that returns a user object or None given a user ID string.
🔧 Debug
advanced
3:00remaining
Why does current_user always appear anonymous even after login?
You call login_user(user) successfully, but in your routes current_user.is_authenticated is always False. What is the most likely cause?
Flask
from flask import Flask
from flask_login import LoginManager, login_user, current_user

app = Flask(__name__)
login_manager = LoginManager(app)

@app.route('/login')
def login():
    user = User.query.first()
    login_user(user)
    return 'Logged in'

@app.route('/profile')
def profile():
    if current_user.is_authenticated:
        return 'User profile'
    else:
        return 'Anonymous user'
AThe Flask app is missing a secret key for session management.
BThe user object passed to login_user is None.
CThe @login_manager.user_loader function is not defined.
DThe login_user function is called outside a request context.
Attempts:
2 left
💡 Hint
Flask-Login requires a user_loader callback to retrieve the user from the session ID.
🧠 Conceptual
expert
2:00remaining
What is the purpose of the @login_manager.unauthorized_handler decorator?
In Flask-Login, what does the function decorated with @login_manager.unauthorized_handler do?
AIt logs out the current user when unauthorized access is detected.
BIt defines the response when a user tries to access a protected route without being logged in.
CIt automatically redirects logged-in users to the home page.
DIt initializes the login manager with the Flask app.
Attempts:
2 left
💡 Hint
Think about what happens when @login_required denies access.

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

  1. 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.
  2. Step 2: Compare options with Flask-Login's purpose

    Creating database models, styling pages, or sending emails are not handled by Flask-Login.
  3. Final Answer:

    To manage user sessions and handle login/logout functionality -> Option B
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    login_manager = LoginManager(); login_manager.init_app(app) -> Option A
  4. 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?
from flask_login import LoginManager
login_manager = LoginManager()

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
medium
A. Raises a TypeError because user_id is a string
B. None, because user_loader must return a boolean
C. A string '42' instead of a User object
D. A User object with ID 42

Solution

  1. Step 1: Understand user_loader function role

    The user_loader function receives a user ID as a string and returns the corresponding User object or None if not found.
  2. Step 2: Analyze the code behavior

    The function converts the string ID to int, then queries the database for that user. If user 42 exists, it returns the User object.
  3. Final Answer:

    A User object with ID 42 -> Option D
  4. Quick Check:

    user_loader returns User object = D [OK]
Hint: user_loader returns User object or None, never boolean [OK]
Common Mistakes:
  • Thinking user_loader returns True/False
  • Assuming user_id must be int already
  • Expecting a string return instead of User object
4. What is the error in this Flask-Login setup code?
login_manager = LoginManager()

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

login_manager.init_app(app)
medium
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

  1. 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.
  2. 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.
  3. Final Answer:

    User.get(user_id) should be User.query.get(user_id) -> Option A
  4. 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

Solution

  1. Step 1: Recall Flask-Login's route protection method

    Flask-Login provides a @login_required decorator to easily protect routes so only logged-in users can access them.
  2. 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.
  3. Final Answer:

    Use the @login_required decorator on the route function -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard