base.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import typing as T
  2. import datetime
  3. from sqlalchemy.inspection import inspect
  4. from sqlalchemy.orm.collections import InstrumentedList
  5. from sqlalchemy_serializer import SerializerMixin
  6. from pycs import app
  7. from pycs import db
  8. class ModelSerializer(SerializerMixin):
  9. date_format = '%s' # Unixtimestamp (seconds)
  10. datetime_format = '%d. %b. %Y %H:%M:%S'
  11. time_format = '%H:%M'
  12. class BaseModel(db.Model, ModelSerializer):
  13. __abstract__ = True
  14. id = db.Column(db.Integer, primary_key=True)
  15. @property
  16. def identifier(self) -> int:
  17. app.logger.warning("REMOVE ME!")
  18. return self.id
  19. def serialize(self) -> dict:
  20. result = self.to_dict()
  21. result["identifier"] = result["id"]
  22. return result
  23. def remove(self, commit=True) -> None:
  24. """
  25. remove this instance from the database
  26. :return:
  27. """
  28. db.session.delete(self)
  29. if commit:
  30. self.commit()
  31. @classmethod
  32. def new(cls, commit=False, **kwargs):
  33. obj = cls(**kwargs)
  34. db.session.add(obj)
  35. if commit:
  36. db.session.commit()
  37. return obj
  38. @classmethod
  39. def get_or_create(cls, **kwargs) -> T.Tuple[T.Any, bool]:
  40. is_new = False
  41. obj = cls.query.filter_by(**kwargs).one_or_none()
  42. if obj is None:
  43. obj = cls.new(commit=False, **kwargs)
  44. is_new = True
  45. return obj, is_new
  46. def commit(self):
  47. db.session.commit()
  48. class NamedBaseModel(BaseModel):
  49. __abstract__ = True
  50. name = db.Column(db.String, nullable=False)
  51. def set_name(self, name: str):
  52. self.name = name
  53. self.commit()