To load a user for Flask Login, you must first create a user model that includes at least the following attributes:
Once you have your user model, you can use Flask Login's UserMixin
class to provide several default methods for the user model, including get_id()
and is_authenticated()
.
Here's an example user model and how to load a user:
from flask_login import UserMixin
from my_app import db
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
password = db.Column(db.String(120))
is_active = db.Column(db.Boolean)
def __init__(self, username, password, is_active):
self.username = username
self.password = password
self.is_active = is_active
def get_id(self):
return str(self.id)
# Loading a user:
from my_app.models import User
def load_user(user_id):
return User.query.get(int(user_id))
In the load_user
function, you retrieve the user from the database using the query.get()
method, which returns the user with the specified user ID or None
if the user does not exist.
Finally, you must register the load_user
function with Flask Login using the LoginManager
object in your Flask app.
from flask_login import LoginManager
from my_app import app
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
The user_loader
decorator tells Flask Login to use the function to load users. Now, the current_user
object is available in your views and templates.
Asked: 2023-07-05 11:35:55 +0000
Seen: 8 times
Last updated: Jul 05 '23