Ask Your Question
3

How can I load a user for Flask login?

asked 2023-07-05 11:35:55 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-05 11:45:02 +0000

lalupa gravatar image

To load a user for Flask Login, you must first create a user model that includes at least the following attributes:

  • id: unique identifier for each user
  • username: username for each user
  • password: hashed password for each user
  • is_active: boolean indicating whether the user account is active

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-05 11:35:55 +0000

Seen: 8 times

Last updated: Jul 05 '23