flask-easy-model

A great base model, bringing Django conveniences to Flask


License
MIT
Install
pip install flask-easy-model==0.4.0

Documentation

flask_easy_model is

E. Z.

from flask_easy_model import get_model
from myproject.extensions import DB


Model = get_model(DB)

class CatModel(Model):

    __tablename__ = 'cat'

    name = DB.Column(DB.String(200), nullable=False, default="Mr. Whiskers")
    breed = DB.Column(DB.String(200), nullable=True, default="tabby")

    def __repr__(self):
        return self.name


$ ipython

kitty = CatModel(name='Garfield', type='lazycat')
kitty.save()

kitty_jr = CatModel.create(name='Garfield Jr.', type='lazycat')

kitty.id # 1
kitty.created_at # 2017-08-31 10:32
kitty.updated_at # 2017-08-31 10:32

kitty.update(name="Garfield Sr.")
kitty.name # "Garfield Sr."

kitty.updated_at # 10:34

newest = CatModel.newest('created_at')
newest[0].name # "Garfield Jr."

oldest = CatModel.oldest('created_at')
oldest[0].name # "Garfield Sr."

kitty.delete()

cats = CatModel.all() # [<Garfield Jr.>]

CatModel.delete_all()

cats = CatModel.all() # []

See the model:


def get_model(DB):

    class Model(DB.Model):
        __abstract__ = True

        id = DB.Column(DB.Integer, primary_key=True)
        created_at = DB.Column(DB.DateTime, default=datetime.utcnow, nullable=False)
        updated_at = DB.Column(DB.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

        def __init__(self, **kwargs):
            DB.Model.__init__(self, **kwargs)

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

        @classmethod
        def delete_all(cls):
            all_objs = cls.query.all()
            for obj in all_objs:
                obj.delete()

        @classmethod
        def all(cls):
            return cls.query.all()

        @classmethod
        def newest(cls, field_name):
            return cls.query.order_by('{field_name} desc'.format(field_name=field_name)).limit(1)

        @classmethod
        def oldest(cls, field_name):
            return cls.query.order_by('{field_name} asc'.format(field_name=field_name)).limit(1)

        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()

    return Model