model.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. import tortoise.models
  2. from .field_generator import field_generator
  3. from .constants import constants
  4. class model(tortoise.models.Model):
  5. """
  6. This is base class for all models in the app. It store base fields, like
  7. ID, and have functions, which is necessary to validate object before
  8. save it in the database.
  9. Fields
  10. ------
  11. id : field_generator.id
  12. ID of the object.
  13. Methods
  14. -------
  15. _validators : dict
  16. Return dict of validators, which would be used to validate fields of
  17. the object. For example, when object have field "name", and function
  18. "val_name(name: str) -> str" would be used to validate it, then that
  19. dict must contain "{ 'name': val_name }".
  20. __validate_item : None
  21. That validate sinle item of the object. To pass validation, result
  22. from validating function must be same as before validaion, and that
  23. function must not raise and error.
  24. __get : any
  25. That return content of given field of object.
  26. validate : object
  27. That run all validators. When any validators found problem with
  28. content of object, then raise an ValueError. If all went nice, then
  29. return self.
  30. Classes
  31. -------
  32. Meta
  33. Fields
  34. ------
  35. app : str
  36. Name of the app.
  37. """
  38. id = field_generator.id()
  39. def __repr__(self) -> str:
  40. result = "Dump of " + self.__class__.__name__
  41. if self.id is not None:
  42. result = result + " #" + str(self.id)
  43. result = result + "\n"
  44. for count in dir(self):
  45. if count[0] == "_":
  46. continue
  47. if count == "id":
  48. continue
  49. if count == "pk":
  50. continue
  51. field = self.__getattribute__(count)
  52. if type(field) is str:
  53. result = result + " " + count + ": \"" + field + "\"\n"
  54. continue
  55. if type(field) is int or type(field) is float:
  56. result = result + " " + count + ": " + str(field) + "\n"
  57. continue
  58. if type(field) is bool:
  59. result = result + " " + count + ": " + str(field) + "\n"
  60. continue
  61. return result
  62. def _validators(self) -> dict:
  63. """
  64. That return dict of fields, which must be validated, with validators
  65. which must be used. Format of the dict is "{ 'name of the field':
  66. validation_function }". By default it is empty, and none of the field
  67. is not validating.
  68. Returns
  69. -------
  70. dict
  71. Dictionary with validators for fields.
  72. """
  73. return dict()
  74. def __validate_item(self, validator: callable, key: str) -> None:
  75. """
  76. It validate single field of the object. When validation is passed,
  77. it return without errors, in other way it raise ValueError.
  78. Parameters
  79. ----------
  80. validator : callable
  81. Validator which would be used to validate field.
  82. key : str
  83. Name of the field.
  84. Raises
  85. ------
  86. ValueError
  87. When field contain incorrect data.
  88. """
  89. try:
  90. if validator(self.__get(key)) == self.__get(key):
  91. return
  92. raise ValueError("Validated value is not same.")
  93. except Exception as error:
  94. value = self.__get(key)
  95. model_name = type(self).__name__
  96. info = "Model \"" + model_name + "\" contain invalid "
  97. info = info + "data in field \"" + key + "\". Content of "
  98. info = info + "field is \"" + value + "\". Found error \""
  99. info = info + str(error) + "\"."
  100. raise ValueError(info)
  101. def __get(self, key: str) -> any:
  102. """
  103. That return field with given name.
  104. Parameters
  105. ----------
  106. key : str
  107. Name of the field.
  108. Returns
  109. -------
  110. any
  111. Value of the key.
  112. """
  113. return self.__getattribute__(key)
  114. def validate(self) -> object:
  115. """
  116. That function make full validation of the object. It validate all
  117. fields, which is in the __validators() dict. When validation had
  118. been passed, it return self. When validation couldn't being passed
  119. it raises ValueError.
  120. Returns
  121. -------
  122. model
  123. Object instance itself.
  124. Raises
  125. ------
  126. ValueError
  127. When any field contain incorrect data.
  128. """
  129. for key, validator in self._validators().items():
  130. self.__validate_item(validator, key)
  131. return self
  132. class Meta:
  133. app = constants.app_name()