Flask-Login User Model Integration with SQLAlchemy

  • Share this:

Code introduction


This code defines a User model that inherits from Flask-Login's UserMixin and combines with SQLAlchemy's Model. It includes fields for user ID, username, and password hash, and provides methods for setting and checking passwords.


Technology Stack : Flask-Login, Flask, SQLAlchemy

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user

def create_user_model(User, db):
    # Define the User model with UserMixin to use built-in user features
    class Userdb(UserMixin, db.Model):
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(100), unique=True, nullable=False)
        password_hash = db.Column(db.String(200), nullable=False)

        def set_password(self, password):
            self.password_hash = generate_password_hash(password)

        def check_password(self, password):
            return check_password_hash(self.password_hash, password)

    return Userdb