base.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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("BaseModel.identifier: REMOVE ME!")
  18. return self.id
  19. def serialize(self) -> dict:
  20. return self.to_dict()
  21. result["identifier"] = result["id"]
  22. return result
  23. def __repr__(self):
  24. attrs = self.serialize()
  25. content = ", ".join([f"{attr}={value}" for attr, value in attrs.items()])
  26. return f"<{self.__class__.__name__}: {content}>"
  27. def remove(self, commit=True) -> None:
  28. """
  29. remove this instance from the database
  30. :return:
  31. """
  32. db.session.delete(self)
  33. if commit:
  34. self.commit()
  35. @classmethod
  36. def new(cls, commit=False, **kwargs):
  37. obj = cls(**kwargs)
  38. db.session.add(obj)
  39. if commit:
  40. db.session.commit()
  41. return obj
  42. @classmethod
  43. def get_or_create(cls, **kwargs) -> T.Tuple[T.Any, bool]:
  44. is_new = False
  45. obj = cls.query.filter_by(**kwargs).one_or_none()
  46. if obj is None:
  47. obj = cls.new(commit=False, **kwargs)
  48. is_new = True
  49. return obj, is_new
  50. def commit(self):
  51. db.session.commit()
  52. class NamedBaseModel(BaseModel):
  53. __abstract__ = True
  54. name = db.Column(db.String, nullable=False)
  55. def set_name(self, name: str):
  56. self.name = name
  57. self.commit()