model.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from public import db
  2. def db_session_commit():
  3. try:
  4. db.session.commit()
  5. except Exception:
  6. db.session.rollback()
  7. raise
  8. class ModelMixin(object):
  9. __slots__ = ()
  10. def __init__(self, **kwargs):
  11. pass
  12. def save(self):
  13. db.session.add(self)
  14. db_session_commit()
  15. return self
  16. def delete(self, commit=True):
  17. db.session.delete(self)
  18. if commit:
  19. db_session_commit()
  20. def add(self):
  21. db.session.add(self)
  22. def update(self, **kwargs):
  23. required_commit = False
  24. for k, v in kwargs.items():
  25. if hasattr(self, k) and getattr(self, k) != v:
  26. required_commit = True
  27. setattr(self, k, v)
  28. if required_commit:
  29. db_session_commit()
  30. return required_commit
  31. @classmethod
  32. def upsert(cls, where, **kwargs):
  33. record = cls.query.filter_by(**where).first()
  34. if record:
  35. record.update(**kwargs)
  36. else:
  37. record = cls(**kwargs).save()
  38. return record
  39. def to_json(self):
  40. if hasattr(self, '__table__'):
  41. return {i.name: getattr(self, i.name) for i in self.__table__.columns}
  42. raise AssertionError('<%r> does not have attribute for __table__' % self)