User Loader Function
Flask-Login stores a user id in the session.
On the next request, it needs to turn that id into a User object.
That’s what the user loader does.
sequenceDiagram
participant B as Browser
participant F as Flask-Login
participant L as your user_loader
participant D as Database
B->>F: request with session cookie
F->>F: read user_id from the session
F->>L: user_loader("7")
L->>D: User.query.get(7)
alt row exists
D-->>L: User
L-->>F: User object
F-->>B: current_user is that user
else row is gone
D-->>L: None
L-->>F: None
F-->>B: current_user is anonymous -- effectively logged out
end
Example
Section titled “Example”from flask_login import LoginManager
login_manager = LoginManager()
@login_manager.user_loader
def load_user(user_id: str):
return User.query.get(int(user_id))Important notes
Section titled “Important notes”user_idcomes from the session, so it’s a string.- Convert types carefully.
- Return
Noneif the user doesn’t exist.
Common pitfalls
Section titled “Common pitfalls”- Forgetting to register the loader → Flask-Login can’t restore sessions
- Querying with the wrong type
- Returning something that isn’t a User model/UserMixin
Where to put this code
Section titled “Where to put this code”In larger apps, user loader registration usually lives in:
authblueprint- app factory initialization
So it’s registered exactly once.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading