BaseModel.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from datetime import datetime, timezone
  4. from typing import TypeVar, Dict, List, Any, Type, Union
  5. # Type variable used in the parse methods below, which should be a subclass of BaseModel.
  6. T = TypeVar("T", bound="BaseModel")
  7. class BaseModel:
  8. def __init__(self, **kwargs) -> None:
  9. self.__dict__.update(kwargs)
  10. self.validate()
  11. # Validates the model, raising an exception if the model is invalid.
  12. def validate(self) -> None:
  13. pass
  14. def __eq__(self, other):
  15. """Checks whether the two models are equal.
  16. :param other: The other model.
  17. :return: True if they are equal, False if they are different.
  18. """
  19. return type(self) == type(other) and self.toDict() == other.toDict()
  20. def __ne__(self, other) -> bool:
  21. """Checks whether the two models are different.
  22. :param other: The other model.
  23. :return: True if they are different, False if they are the same.
  24. """
  25. return type(self) != type(other) or self.toDict() != other.toDict()
  26. def toDict(self) -> Dict[str, Any]:
  27. """Converts the model into a serializable dictionary"""
  28. return self.__dict__
  29. @staticmethod
  30. def parseModel(model_class: Type[T], values: Union[T, Dict[str, Any]]) -> T:
  31. """Parses a single model.
  32. :param model_class: The model class.
  33. :param values: The value of the model, which is usually a dictionary, but may also be already parsed.
  34. :return: An instance of the model_class given.
  35. """
  36. if isinstance(values, dict):
  37. return model_class(**values)
  38. return values
  39. @classmethod
  40. def parseModels(cls, model_class: Type[T], values: List[Union[T, Dict[str, Any]]]) -> List[T]:
  41. """Parses a list of models.
  42. :param model_class: The model class.
  43. :param values: The value of the list. Each value is usually a dictionary, but may also be already parsed.
  44. :return: A list of instances of the model_class given.
  45. """
  46. return [cls.parseModel(model_class, value) for value in values]
  47. @staticmethod
  48. def parseDate(date: Union[str, datetime]) -> datetime:
  49. """Parses the given date string.
  50. :param date: The date to parse.
  51. :return: The parsed date.
  52. """
  53. if isinstance(date, datetime):
  54. return date
  55. return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)