如何在Flask中实现MIXIN?

时间:2017-04-13 07:54:46

标签: python sqlalchemy

所以我没有使用基类,而是想使用Mixin,我没有找到很多关于在FLASK中使用Mixins的文档。任何人都可以帮助我如何实现Mixins而不是这个抽象的Base类?

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)

1 个答案:

答案 0 :(得分:4)

关于mixins和sqlalchemy的文档在这里:http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html

根据您的具体示例,这里有一些代码,基于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()

然后你可以使用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)