123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- import typing as T
- import datetime
- from sqlalchemy.inspection import inspect
- from sqlalchemy.orm.collections import InstrumentedList
- from sqlalchemy_serializer import SerializerMixin
- from pycs import app
- from pycs import db
- class ModelSerializer(SerializerMixin):
- date_format = '%s' # Unixtimestamp (seconds)
- datetime_format = '%d. %b. %Y %H:%M:%S'
- time_format = '%H:%M'
- class BaseModel(db.Model, ModelSerializer):
- __abstract__ = True
- id = db.Column(db.Integer, primary_key=True)
- @property
- def identifier(self) -> int:
- app.logger.warning("REMOVE ME!")
- return self.id
- def serialize(self) -> dict:
- result = self.to_dict()
- result["identifier"] = result["id"]
- return result
- def remove(self, commit=True) -> None:
- """
- remove this instance from the database
- :return:
- """
- db.session.delete(self)
- if commit:
- self.commit()
- @classmethod
- def new(cls, commit=False, **kwargs):
- obj = cls(**kwargs)
- db.session.add(obj)
- if commit:
- db.session.commit()
- return obj
- @classmethod
- def get_or_create(cls, **kwargs) -> T.Tuple[T.Any, bool]:
- is_new = False
- obj = cls.query.filter_by(**kwargs).one_or_none()
- if obj is None:
- obj = cls.new(commit=False, **kwargs)
- is_new = True
- return obj, is_new
- def commit(self):
- db.session.commit()
- class NamedBaseModel(BaseModel):
- __abstract__ = True
- name = db.Column(db.String, nullable=False)
- def set_name(self, name: str):
- self.name = name
- self.commit()
|