6
0

base.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. from __future__ import annotations
  2. import typing as T
  3. from flask import abort
  4. from sqlalchemy_serializer import SerializerMixin
  5. from pycs import db
  6. from pycs.database.util import commit_on_return
  7. class BaseModel(db.Model, SerializerMixin):
  8. """ Base model class """
  9. __abstract__ = True
  10. # setup of the SerializerMixin
  11. date_format = '%s' # Unixtimestamp (seconds)
  12. datetime_format = '%d. %b. %Y %H:%M:%S'
  13. time_format = '%H:%M'
  14. id = db.Column(db.Integer, primary_key=True)
  15. serialize_only = ("id",)
  16. def __repr__(self):
  17. attrs = self.serialize()
  18. content = ", ".join([f"{attr}={value}" for attr, value in attrs.items()])
  19. return f"<{self.__class__.__name__}: {content}>"
  20. def serialize(self) -> dict:
  21. """ default model serialize method. adds identifier as alias for id """
  22. res = self.to_dict()
  23. res["identifier"] = self.id
  24. return res
  25. @commit_on_return
  26. def delete(self) -> dict:
  27. """
  28. delete this instance from the database
  29. :return: serialized self
  30. """
  31. db.session.delete(self)
  32. dump = self.serialize()
  33. return dump
  34. # do an alias
  35. remove = delete
  36. @classmethod
  37. def new(cls, commit: bool = True, **kwargs):
  38. """ creates a new object. optionally commits the created object. """
  39. obj = cls(**kwargs)
  40. db.session.add(obj)
  41. if commit:
  42. obj.commit()
  43. return obj
  44. @classmethod
  45. def get_or_create(cls, **kwargs) -> T.Tuple[BaseModel, bool]:
  46. """ get an object from the DB based on the kwargs, or create an object with these. """
  47. is_new = False
  48. obj = cls.query.filter_by(**kwargs).one_or_none()
  49. if obj is None:
  50. obj = cls.new(commit=False, **kwargs)
  51. is_new = True
  52. return obj, is_new
  53. @classmethod
  54. def get_or_404(cls, obj_id: int) -> BaseModel:
  55. """ get an object for the given id or raise 404 error if the object is not present """
  56. obj = cls.query.get(obj_id)
  57. if obj is None:
  58. abort(404, f"{cls.__name__} with ID {obj_id} could not be found!")
  59. return obj
  60. @staticmethod
  61. def commit():
  62. """ commit current session """
  63. db.session.commit()
  64. @staticmethod
  65. def flush():
  66. """ flush current session """
  67. db.session.flush()
  68. class NamedBaseModel(BaseModel):
  69. """ Extends the base model with a name attribute. """
  70. __abstract__ = True
  71. name = db.Column(db.String, nullable=False)
  72. serialize_only = BaseModel.serialize_only + ("name",)
  73. @commit_on_return
  74. def set_name(self, name: str):
  75. """ set the name attribute """
  76. self.name = name