Bird
Raised Fist0
Flaskframework~5 mins

Current_user object in Flask

Choose your learning style10 modes available
Introduction

The current_user object helps you know who is using your web app right now. It makes it easy to check if someone is logged in and get their info.

To show a welcome message with the user's name after they log in.
To restrict access to certain pages only to logged-in users.
To customize content based on the user's preferences or role.
To log user actions or track who made changes.
To display user profile details on their dashboard.
Syntax
Flask
from flask_login import current_user

# Use current_user in your route or template
if current_user.is_authenticated:
    username = current_user.username
else:
    username = 'Guest'

current_user is provided by the flask_login extension.

You can access user properties like username if your user model has them.

Examples
Check if the user is logged in and greet them by name.
Flask
from flask_login import current_user

@app.route('/profile')
def profile():
    if current_user.is_authenticated:
        return f"Hello, {current_user.username}!"
    else:
        return "Please log in to see your profile."
Redirect users who are not logged in to the login page.
Flask
from flask import redirect
from flask_login import current_user

@app.route('/dashboard')
def dashboard():
    if not current_user.is_authenticated:
        return redirect('/login')
    # Show dashboard for logged-in user
    return f"Welcome to your dashboard, {current_user.username}!"
Sample Program

This Flask app logs in a user named Alice when you visit /login. Then, visiting /hello shows a greeting using current_user.username. If you are not logged in, /hello redirects you to login.

Flask
from flask import Flask, redirect, url_for
from flask_login import LoginManager, UserMixin, login_user, current_user, login_required

app = Flask(__name__)
app.secret_key = 'secret'

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

# Simple user class
class User(UserMixin):
    def __init__(self, id, username):
        self.id = id
        self.username = username

# User loader for flask-login
@login_manager.user_loader
def load_user(user_id):
    if user_id == '1':
        return User('1', 'Alice')
    return None

@app.route('/login')
def login():
    user = User('1', 'Alice')
    login_user(user)
    return 'Logged in as Alice'

@app.route('/hello')
@login_required
def hello():
    return f'Hello, {current_user.username}!'

if __name__ == '__main__':
    app.run(debug=False)
OutputSuccess
Important Notes

Always protect routes that use current_user with @login_required to avoid errors.

current_user.is_authenticated is a quick way to check if someone is logged in.

You can add any user info to your user class and access it via current_user.

Summary

current_user tells you who is using your app right now.

Use it to check login status and get user details easily.

Protect routes with @login_required to safely use current_user.

Practice

(1/5)
1. What does the current_user object represent in a Flask app?
easy
A. A list of all users in the database
B. The admin user only
C. The user who is currently logged in
D. A random user from the database

Solution

  1. Step 1: Understand the purpose of current_user

    The current_user object is provided by Flask-Login to represent the user who is currently logged in to the app.
  2. Step 2: Compare options with this meaning

    Only the user who is currently logged in correctly describes current_user as the user currently logged in. Other options describe unrelated concepts.
  3. Final Answer:

    The user who is currently logged in -> Option C
  4. Quick Check:

    current_user = logged-in user [OK]
Hint: Remember: current_user means the active logged-in user [OK]
Common Mistakes:
  • Thinking current_user is a list of users
  • Confusing current_user with admin user only
  • Assuming current_user is random
2. Which import is required to use current_user in a Flask app?
easy
A. from flask_login import current_user
B. from flask import current_user
C. import current_user from flask
D. from flask_login import login_user

Solution

  1. Step 1: Identify the correct module for current_user

    The current_user object is part of the Flask-Login extension, so it must be imported from flask_login.
  2. Step 2: Check the import syntax

    from flask_login import current_user uses the correct syntax: from flask_login import current_user. Other options either import from the wrong place or use incorrect syntax.
  3. Final Answer:

    from flask_login import current_user -> Option A
  4. Quick Check:

    Import current_user from flask_login [OK]
Hint: Import current_user from flask_login, not flask [OK]
Common Mistakes:
  • Importing current_user from flask instead of flask_login
  • Using incorrect import syntax
  • Confusing login_user with current_user
3. Given this Flask route code:
@app.route('/profile')
@login_required
def profile():
    return f"Hello, {current_user.username}!"

What will be the output if a logged-in user has username 'Alice'?
medium
A. Hello, Alice!
B. Hello, current_user!
C. Hello, None!
D. Error: current_user not defined

Solution

  1. Step 1: Understand the use of @login_required and current_user

    The decorator @login_required ensures only logged-in users can access the route. current_user.username accesses the username of the logged-in user.
  2. Step 2: Substitute the username value

    Since the logged-in user's username is 'Alice', the returned string will be "Hello, Alice!".
  3. Final Answer:

    Hello, Alice! -> Option A
  4. Quick Check:

    Logged-in username shown correctly [OK]
Hint: Use @login_required to safely access current_user.username [OK]
Common Mistakes:
  • Forgetting @login_required causes errors
  • Using current_user without .username
  • Expecting literal 'current_user' in output
4. What is the likely cause of this error in a Flask app?
RuntimeError: Working outside of request context.

Code snippet:
print(current_user.is_authenticated)
medium
A. User is not logged in
B. Missing import of current_user
C. Flask app not running
D. Trying to access current_user outside a request or route

Solution

  1. Step 1: Understand the error message

    The error "Working outside of request context" means code is trying to use request-specific objects like current_user outside a web request or route function.
  2. Step 2: Identify cause related to current_user

    Accessing current_user must happen inside a route or request context. Printing it outside causes this runtime error.
  3. Final Answer:

    Trying to access current_user outside a request or route -> Option D
  4. Quick Check:

    current_user needs request context [OK]
Hint: Use current_user only inside routes or request context [OK]
Common Mistakes:
  • Assuming missing import causes this error
  • Thinking user login status causes this error
  • Believing app not running causes this error
5. You want to show a special message only to logged-in users using current_user. Which code snippet correctly checks login status before showing the message?
hard
A. if current_user: print('Welcome back!') else: print('Please log in.')
B. if current_user.is_authenticated: print('Welcome back!') else: print('Please log in.')
C. if current_user.logged_in: print('Welcome back!') else: print('Please log in.')
D. if current_user.is_active: print('Welcome back!') else: print('Please log in.')

Solution

  1. Step 1: Identify the correct property to check login status

    The current_user object has a property is_authenticated that returns True if the user is logged in.
  2. Step 2: Verify the code snippet uses is_authenticated properly

    if current_user.is_authenticated: print('Welcome back!') else: print('Please log in.') uses current_user.is_authenticated correctly to decide which message to print. Other options use incorrect or non-existent properties.
  3. Final Answer:

    if current_user.is_authenticated: print('Welcome back!') else: print('Please log in.') -> Option B
  4. Quick Check:

    Use is_authenticated to check login [OK]
Hint: Check current_user.is_authenticated for login status [OK]
Common Mistakes:
  • Using current_user.logged_in instead of is_authenticated
  • Checking current_user directly without property
  • Confusing is_active with login status
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