Nenhuma descrição
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

base_classes.py 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. # -*- coding: utf-8 -*-
  2. ## @package lodel.leapi.datahandlers.base_classes Define all base/abstract class for data handlers
  3. #
  4. # Contains custom exceptions too
  5. import copy
  6. import importlib
  7. import inspect
  8. from lodel import logger
  9. class FieldValidationError(Exception):
  10. pass
  11. ## @brief Base class for all data handlers
  12. class DataHandler(object):
  13. __HANDLERS_MODULES = ('datas_base', 'datas', 'references')
  14. ## @brief Stores the DataHandler childs classes indexed by name
  15. __base_handlers = None
  16. ## @brief Stores custom datahandlers classes indexed by name
  17. # @todo do it ! (like plugins, register handlers... blablabla)
  18. __custom_handlers = dict()
  19. help_text = 'Generic Field Data Handler'
  20. ## @brief List fields that will be exposed to the construct_data_method
  21. _construct_datas_deps = []
  22. ## @brief constructor
  23. # @param internal False | str : define whether or not a field is internal
  24. # @param immutable bool : indicates if the fieldtype has to be defined in child classes of LeObject or if it is
  25. # designed globally and immutable
  26. # @param **args
  27. # @throw NotImplementedError if it is instanciated directly
  28. def __init__(self, internal=False, immutable=False, primary_key = False, **args):
  29. if self.__class__ == DataHandler:
  30. raise NotImplementedError("Abstract class")
  31. self.primary_key = primary_key
  32. self.internal = internal # Check this value ?
  33. self.immutable = bool(immutable)
  34. for argname, argval in args.items():
  35. setattr(self, argname, argval)
  36. ## Fieldtype name
  37. @staticmethod
  38. def name(cls):
  39. return cls.__module__.split('.')[-1]
  40. def is_primary_key(self):
  41. return self.primary_key
  42. ## @brief checks if a fieldtype is internal
  43. # @return bool
  44. def is_internal(self):
  45. return self.internal is not False
  46. ## @brief calls the data_field defined _check_data_value() method
  47. # @return tuple (value, error|None)
  48. def check_data_value(self, value):
  49. return self._check_data_value(value)
  50. def _check_data_value(self, value):
  51. return value, None
  52. ## @brief checks if this class can override the given data handler
  53. # @param data_handler DataHandler
  54. # @return bool
  55. def can_override(self, data_handler):
  56. if data_handler.__class__.base_type != self.__class__.base_type:
  57. return False
  58. return True
  59. ## @brief Build field value
  60. # @param emcomponent EmComponent : An EmComponent child class instance
  61. # @param fname str : The field name
  62. # @param datas dict : dict storing fields values (from the component)
  63. # @param cur_value : the value from the current field (identified by fieldname)
  64. # @return the value
  65. # @throw RunTimeError if data construction fails
  66. def construct_data(self, emcomponent, fname, datas, cur_value):
  67. emcomponent_fields = emcomponent.fields()
  68. fname_data_handler = None
  69. if fname in emcomponent_fields:
  70. fname_data_handler = DataHandler.from_name(emcomponent_fields[fname])
  71. if fname in datas.keys():
  72. return cur_value
  73. elif fname_data_handler is not None and hasattr(fname_data_handler, 'default'):
  74. return fname_data_handler.default
  75. elif fname_data_handler is not None and fname_data_handler.nullable:
  76. return None
  77. return RuntimeError("Unable to construct data for field %s", fname)
  78. ## @brief Check datas consistency
  79. # @param emcomponent EmComponent : An EmComponent child class instance
  80. # @param fname : the field name
  81. # @param datas dict : dict storing fields values
  82. # @return an Exception instance if fails else True
  83. # @todo A implémenter
  84. def check_data_consistency(self, emcomponent, fname, datas):
  85. return True
  86. ## @brief This method is use by plugins to register new data handlers
  87. @classmethod
  88. def register_new_handler(cls, name, data_handler):
  89. if not inspect.isclass(data_handler):
  90. raise ValueError("A class was expected but %s given" % type(data_handler))
  91. if not issubclass(data_handler, DataHandler):
  92. raise ValueError("A data handler HAS TO be a child class of DataHandler")
  93. cls.__custom_handlers[name] = data_handler
  94. @classmethod
  95. def load_base_handlers(cls):
  96. if cls.__base_handlers is None:
  97. cls.__base_handlers = dict()
  98. for module_name in cls.__HANDLERS_MODULES:
  99. module = importlib.import_module('lodel.leapi.datahandlers.%s' % module_name)
  100. for name, obj in inspect.getmembers(module):
  101. if inspect.isclass(obj):
  102. logger.debug("Load data handler %s.%s" % (obj.__module__, obj.__name__))
  103. cls.__base_handlers[name.lower()] = obj
  104. return copy.copy(cls.__base_handlers)
  105. ## @brief given a field type name, returns the associated python class
  106. # @param fieldtype_name str : A field type name (not case sensitive)
  107. # @return DataField child class
  108. # @todo implements custom handlers fetch
  109. # @note To access custom data handlers it can be cool to preffix the handler name by plugin name for example ? (to ensure name unicity)
  110. @classmethod
  111. def from_name(cls, name):
  112. name = name.lower()
  113. if name not in cls.__base_handlers:
  114. raise NameError("No data handlers named '%s'" % (name,))
  115. return cls.__base_handlers[name]
  116. ## @brief Return the module name to import in order to use the datahandler
  117. # @param data_handler_name str : Data handler name
  118. # @return a str
  119. @classmethod
  120. def module_name(cls, name):
  121. name = name.lower()
  122. handler_class = cls.from_name(name)
  123. return '{module_name}.{class_name}'.format(
  124. module_name = handler_class.__module__,
  125. class_name = handler_class.__name__
  126. )
  127. ## @brief __hash__ implementation for fieldtypes
  128. def __hash__(self):
  129. hash_dats = [self.__class__.__module__]
  130. for kdic in sorted([k for k in self.__dict__.keys() if not k.startswith('_')]):
  131. hash_dats.append((kdic, getattr(self, kdic)))
  132. return hash(tuple(hash_dats))
  133. ## @brief Base class for datas data handler (by opposition with references)
  134. class DataField(DataHandler):
  135. ## @brief Instanciates a new fieldtype
  136. # @param nullable bool : is None allowed as value ?
  137. # @param uniq bool : Indicates if a field should handle a uniq value
  138. # @param primary bool : If true the field is a primary key
  139. # @param internal str|False: if False, that field is not internal. Other values cans be "autosql" or "internal"
  140. # @param **kwargs : Other arguments
  141. # @throw NotImplementedError if called from bad class
  142. def __init__(self, internal=False, nullable=True, uniq=False, primary=False, **kwargs):
  143. if self.__class__ == DataField:
  144. raise NotImplementedError("Abstract class")
  145. super().__init__(internal, **kwargs)
  146. self.nullable = nullable
  147. self.uniq = uniq
  148. self.primary = primary
  149. if 'defaults' in kwargs:
  150. self.default, error = self.check_data_value(kwargs['default'])
  151. if error:
  152. raise error
  153. del(args['default'])
  154. def check_data_value(self, value):
  155. if value is None:
  156. if not self.nullable:
  157. return None, TypeError("'None' value but field is not nullable")
  158. return None, None
  159. return super().check_data_value(value)
  160. ## @brief Abstract class for all references
  161. #
  162. # References are fields that stores a reference to another
  163. # editorial object
  164. class Reference(DataHandler):
  165. ## @brief Instanciation
  166. # @param allowed_classes list | None : list of allowed em classes if None no restriction
  167. # @param internal bool : if False, the field is not internal
  168. # @param **kwargs : other arguments
  169. def __init__(self, allowed_classes = None, internal=False, **kwargs):
  170. self.__allowed_classes = None if allowed_classes is None else set(allowed_classes)
  171. super().__init__(internal=internal, **kwargs)
  172. ## @brief Check value
  173. # @param value *
  174. # @return tuple(value, exception)
  175. # @todo implement the check when we have LeObject to check value
  176. def _check_data_value(self, value):
  177. return value, None
  178. if isinstance(value, lodel.editorial_model.components.EmClass):
  179. value = [value]
  180. for elt in value:
  181. if not issubclass(elt.__class__, EmClass):
  182. return None, FieldValidationError("Some elements of this references are not EmClass instances")
  183. if self.__allowed_classes is not None:
  184. if not isinstance(elt, self.__allowed_classes):
  185. return None, FieldValidationError("Some element of this references are not valids (don't fit with allowed_classes")
  186. return value
  187. ## @brief This class represent a data_handler for single reference to another object
  188. #
  189. # The fields using this data handlers are like "foreign key" on another object
  190. class SingleRef(Reference):
  191. def __init__(self, allowed_classes = None, **kwargs):
  192. super().__init__(allowed_classes = allowed_classes)
  193. def _check_data_value(self, value):
  194. val, expt = super()._check_data_value(value)
  195. if not isinstance(expt, Exception):
  196. if len(val) > 1:
  197. return None, FieldValidationError("Only single values are allowed for SingleRef fields")
  198. return val, expt
  199. ## @brief This class represent a data_handler for multiple references to another object
  200. #
  201. # The fields using this data handlers are like SingleRef but can store multiple references in one field
  202. # @note SQL implementation could be tricky
  203. class MultipleRef(Reference):
  204. def __init__(self, allowed_classes = None, **kwargs):
  205. super().__init__(allowed_classes = allowed_classes)