1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- import typing as T
- import datetime
- 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("BaseModel.identifier: REMOVE ME!")
- return self.id
- def serialize(self) -> dict:
- return self.to_dict()
- result["identifier"] = result["id"]
- return result
- def __repr__(self):
- attrs = self.serialize()
- content = ", ".join([f"{attr}={value}" for attr, value in attrs.items()])
- return f"<{self.__class__.__name__}: {content}>"
- 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()
|