0
0
Flaskframework~30 mins

Flask-Login extension - Mini Project: Build & Apply

Choose your learning style9 modes available
User Login System with Flask-Login Extension
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Set a secret key for sessions and protect the profile route with @login_required decorator.