Setting Up Flask-Login
Flask on its own has no idea what "logged in" means. It does not know how to remember who you are between page visits, or how to block someone from a page they are not allowed to see. Flask-Login is a package that adds all of that.
Think of it this way: you have built the building with Flask. Flask-Login is the security desk you put at the front entrance. It tracks who has checked in and stops anyone without a pass from reaching the locked rooms.
Installing Flask-Login
Remember how we installed Flask? We went to the terminal and ran:
pip install flask
Flask-Login works exactly the same way:
pip install flask-login
That is it. One line and it is ready to use.
What is a User object?
Before we write any code, let us think about what a "user" means in a program.
When you have a bank account, the bank stores your information somewhere - your name, your account number, your balance. They can find everything about you just from your account number.
Your school gave you a registration number or an index number. That number uniquely identifies you. With it, the school can find your grades, your class, your parents' contacts - everything.
When you sign up on WhatsApp or Facebook, they do the same thing. They take your details - name, phone number or email - and assign you a unique ID. Every time you open the app and type your password, they find the ID attached to those details and suddenly they know your messages, your friends, your profile. That ID is the key to everything about you.
A User object in code is the same idea. It is a way of representing a real person inside a program. It holds their username, their ID, and whatever else the app needs to know about them.
Without a User object, Flask-Login has no one to remember.
Remember classes?
You already know that a class is a blueprint, and you create objects from it. You did this with PookieDB - you wrote a Patient class and created patient objects from it.
Flask-Login comes with a class called UserMixin. You do not write it - it is built into Flask-Login. You just use it by adding it to your own User class.
Here is why you need it: Flask-Login needs to ask your User object certain standard questions - "is this person logged in?", "are they active?", "what is their ID?". If you wrote your User class completely from scratch, you would have to write the code to answer every one of those questions yourself.
UserMixin is a ready-made set of answers. Add it to your User class and Flask-Login can work with your users straight away. Here is how it looks:
Without UserMixin - you would have to write all of this yourself:
class User:
def is_authenticated(self): return True
def is_active(self): return True
def is_anonymous(self): return False
def get_id(self): return str(self.id)
With UserMixin - you write none of it:
from flask_login import UserMixin
class User(UserMixin, pookiedb.Model):
...
UserMixin handles all four of those methods for you. You just put it in the class definition alongside pookiedb.Model.
The user loader function
Flask-Login stores the logged-in user's ID between requests. But it needs a way to turn that ID back into an actual User object whenever a new request comes in.
Analogy: the security desk stamps your visitor badge with a number when you check in. Every time you walk through a door, the desk looks up that number in the register to confirm who you are. The user loader is the person doing that lookup.
You write this function once and Flask-Login calls it automatically on every request:
@login_manager.user_loader
def load_user(user_id):
return User.objects.get(id=user_id)
It receives an ID, looks up that user in PookieDB, and returns them. One function. Flask-Login handles everything else.
The complete wiring
Here is a minimal app.py that sets everything up, with every new line explained:
from flask import Flask, render_template
from flask_login import LoginManager # the security desk
from database import User # your User model (built next page)
app = Flask(__name__)
app.secret_key = "change-this-to-something-random" # Flask needs this to store session data securely
login_manager = LoginManager(app) # attach the security desk to your app
login_manager.login_view = "login" # tell it which route is the login page
@login_manager.user_loader # register the lookup function
def load_user(user_id):
return User.objects.get(id=user_id) # find the user by their ID and return them
@app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
app.secret_key is something Flask needs to store information about who is logged in between requests. Set it to any random string - just do not leave it blank.
The User model and full login form come on the next pages. For now, understand what each piece does.
Challenge
Read through the wiring above and cover the comments with your hand. Can you explain in your own words what each line does? Try saying it out loud. If you can explain it simply, you understand it.
← What is Authentication? Next: Storing Users with PookieDB →