6
0

base.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import datetime
  2. import typing as T
  3. from flask import abort
  4. from sqlalchemy_serializer import SerializerMixin
  5. from pycs import app
  6. from pycs import db
  7. class ModelSerializer(SerializerMixin):
  8. date_format = '%s' # Unixtimestamp (seconds)
  9. datetime_format = '%d. %b. %Y %H:%M:%S'
  10. time_format = '%H:%M'
  11. class BaseModel(db.Model, ModelSerializer):
  12. __abstract__ = True
  13. id = db.Column(db.Integer, primary_key=True)
  14. serialize_only = ("id",)
  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=True, **kwargs):
  37. obj = cls(**kwargs)
  38. db.session.add(obj)
  39. if commit:
  40. obj.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. @classmethod
  51. def get_or_404(cls, obj_id: int) -> T.Any:
  52. obj = cls.query.get(obj_id)
  53. if obj is None:
  54. abort(404, f"{cls.__name__} with ID {obj_id} could not be found!")
  55. return obj
  56. def commit(self):
  57. db.session.commit()
  58. class NamedBaseModel(BaseModel):
  59. __abstract__ = True
  60. name = db.Column(db.String, nullable=False)
  61. serialize_only = BaseModel.serialize_only + ("name", )
  62. def set_name(self, name: str, commit: bool = True):
  63. self.name = name
  64. if commit:
  65. self.commit()