[Python][Flask] Flask-Login, @login_manager.user_loader()
@login_manager.user_loader()
When working with Flask-login, it's common to define a function like load_user() in app.py and decorate it with @login_manger.user_loader. At first glance, it might seem like this function belongs in the Controller part in the MVC pattern, but it's not quite right.
Probable confusion
Let's suppose that there is a User class with a method like find_user() that looks up a user by ID in a project. This might cause a confusion that User.find_user() can be called directly in routes instead of defining load_user() in app.py, which actually call User.find_user().
The purpose of app.load_user()
Flask-Login uses app.load_user() is a hook to rebuild the user object during requests. When a user is logged in, Flask-Login stores their ID in the session. On each request, it calls app.load_user(). In other words, app.load_user() is custom logic to be called when a user logged in, and this is indicated by the decorator to Flask-Login.
@login_manager.user_loader
def load_user(user_id):
return User.find_user(user_id=user_id)
Why it belongs in app.py
app.load_user() is not part of the domain logic, but it's infrastructure logic. It's to connect the user lookup logic (User.find_user()) to Flask-Login.
Comments
Post a Comment