3

So instead of using a Base class, i want to make use of Mixin's, i haven't found much documentation about using Mixins in FLASK. Can anyone help out with how i can implement Mixins instead of this abstract Base class?

class Base(db.Model):
    """
    Base class for models.

    Define the base class for the models so others can inherit from it.
    """

    __abstract__ = True

    def save(self):
        """
        Save to database.

        Save instance of the object to database and commit.
        """
        db.session.add(self)
        db.session.commit()

    def delete(self):
        """
        Delete from database.

        Deletes instance of an object from database
        """
        db.session.delete(self)
        db.session.commit()


class User(Base):
    """
    Set up the User model.

    Set up the properties of the User object and the table name too.
    """

    __tablename__ = 'users'
    user_id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32), unique=True, index=True,
                         nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)
    date_created = db.Column(
        db.DateTime, default=datetime.now(), nullable=False)
    date_modified = db.Column(
        db.DateTime, default=datetime.now(),
        onupdate=datetime.now(), nullable=False)

    def hash_password(self, password):
        """
        Hash user password.

        Passwords shouldn't be stored as string so we hash them.
        """
        self.password_hash = generate_password_hash(password)
davidism
  • 121,510
  • 29
  • 395
  • 339
proton
  • 1,639
  • 6
  • 18
  • 30

1 Answers1

7

documentation on mixins and sqlalchemy are here: http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html

for your specific example, here is some code for you, based on https://github.com/mjhea0/flask-tracking

from app import db

class CRUDMixin(object):
    __table_args__ = {'extend_existing': True}

    id = Column(db.Integer, primary_key=True)

    @classmethod
    def get_by_id(cls, id):
        if any(
            (isinstance(id, str) and id.isdigit(),
             isinstance(id, (int, float))),
        ):
            return cls.query.get(int(id))
        return None

    @classmethod
    def create(cls, **kwargs):
        instance = cls(**kwargs)
        return instance.save()

    def update(self, commit=True, **kwargs):
        for attr, value in kwargs.iteritems():
            setattr(self, attr, value)
        return commit and self.save() or self

    def save(self, commit=True):
        db.session.add(self)
        if commit:
            db.session.commit()
        return self

    def delete(self, commit=True):
        db.session.delete(self)
        return commit and db.session.commit()

Then you can use that mixin:

from app import db
from mymixins import CRUDMixin

class User(CRUDMixin, db.Model):

    """
    Set up the User model.

    Set up the properties of the User object and the table name too.
    """

    __tablename__ = 'users'
    username = db.Column(db.String(32), unique=True, index=True,
                         nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)
    date_created = db.Column(
        db.DateTime, default=datetime.now(), nullable=False)
    date_modified = db.Column(
        db.DateTime, default=datetime.now(),
        onupdate=datetime.now(), nullable=False)

    def hash_password(self, password):
        """
        Hash user password.

        Passwords shouldn't be stored as string so we hash them.
        """
        self.password_hash = generate_password_hash(password)
polo
  • 1,352
  • 2
  • 16
  • 35