0
0
Flaskframework~30 mins

Current_user object in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the current_user Object in Flask
📖 Scenario: You are building a simple Flask web app that shows a personalized greeting to the logged-in user.
🎯 Goal: Create a Flask app that uses the current_user object to display the username on the homepage.
📋 What You'll Learn
Create a Flask app with Flask-Login installed
Set up a user loader and a User class
Use the current_user object to get the logged-in user's username
Display the username on the homepage
💡 Why This Matters
🌍 Real World
Web apps often need to know who is logged in to personalize content and control access.
💼 Career
Understanding how to use current_user is essential for building secure and user-friendly Flask web applications.
Progress0 / 4 steps
1
Set up Flask app and User class
Create a Flask app instance called app and define a User class with an __init__ method that takes id and username as parameters. Also, import Flask and flask_login.
Flask
Need a hint?

Start by creating the Flask app and a User class that inherits from UserMixin.

2
Configure Flask-Login and user loader
Create a LoginManager instance called login_manager and initialize it with app. Then, define a user loader function called load_user that takes user_id and returns a User object with id=user_id and username='TestUser'.
Flask
Need a hint?

Use LoginManager to manage user sessions and define a user loader function.

3
Create a route that uses current_user
Create a route for '/' using @app.route. Inside the view function called home, return a string that says f"Hello, {current_user.username}!". Import current_user from flask_login.
Flask
Need a hint?

Use current_user.username inside the route to greet the user.

4
Add secret key and run the app
Set app.secret_key to 'secret123' and add the code to run the app with app.run(debug=True).
Flask
Need a hint?

Set a secret key for sessions and add the code to run the Flask app.