Skip to content

Instantly share code, notes, and snippets.

@alpden550
Created February 19, 2020 13:59
Show Gist options
  • Save alpden550/d713d0e360f21e3aff344112b290ecf0 to your computer and use it in GitHub Desktop.
Save alpden550/d713d0e360f21e3aff344112b290ecf0 to your computer and use it in GitHub Desktop.
from . import db
from .exceptions import SaveObjectException
# From Mike Bayer's "Building the app" talk
# https://speakerdeck.com/zzzeek/building-the-app
class BaseMixin:
"""
A mixin that adds a surrogate integer 'primary key' column named ``id``
to any declarative-mapped class and other usefull stuff.
"""
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
@classmethod
def create(cls, **kwargs):
"""Create a new record and save it the database."""
instance = cls(**kwargs)
return instance.save()
def update(self, commit=True, **kwargs):
"""Update specific fields of a record."""
for attr, value in kwargs.items():
setattr(self, attr, value)
return commit and self.save() or self
def save(self, commit=True):
"""Save the record."""
db.session.add(self)
if commit:
try:
db.session.commit()
except Exception as ex:
db.session.rollback()
raise SaveObjectException(ex)
else:
return self
def delete(self, commit=True):
"""Remove the record from the database."""
db.session.delete(self)
return commit and db.session.commit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment