No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base_classes.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. import warnings
  9. from lodel.context import LodelContext
  10. LodelContext.expose_modules(globals(), {
  11. 'lodel.exceptions': ['LodelException', 'LodelExceptions',
  12. 'LodelFatalError', 'DataNoneValid', 'FieldValidationError'],
  13. 'lodel.leapi.datahandlers.exceptions': ['LodelDataHandlerConsistencyException', 'LodelDataHandlerException'],
  14. 'lodel.logger': 'logger'})
  15. ##@brief Base class for all data handlers
  16. #@ingroup lodel2_datahandlers
  17. class DataHandler(object):
  18. base_type = "type"
  19. _HANDLERS_MODULES = ('datas_base', 'datas', 'references')
  20. ##@brief Stores the DataHandler childs classes indexed by name
  21. _base_handlers = None
  22. ##@brief Stores custom datahandlers classes indexed by name
  23. # @todo do it ! (like plugins, register handlers... blablabla)
  24. __custom_handlers = dict()
  25. help_text = 'Generic Field Data Handler'
  26. ##@brief List fields that will be exposed to the construct_data_method
  27. _construct_datas_deps = []
  28. directly_editable = True
  29. ##@brief constructor
  30. # @param **kwargs dict
  31. # - internal False | str : define whether or not a field is internal
  32. # - immutable bool : indicates if the fieldtype has to be defined in child classes of LeObject or if it is designed globally and immutable
  33. # - nullable bool
  34. # - uniq bool
  35. # - primary_key bool
  36. # - default mixed
  37. # @throw NotImplementedError if it is instanciated directly
  38. def __init__(self, **kwargs):
  39. if self.__class__ == DataHandler:
  40. raise NotImplementedError("Abstract class")
  41. self.__arguments = kwargs
  42. self.nullable = True
  43. self.uniq = False
  44. self.immutable = False
  45. self.primary_key = False
  46. self.internal = False
  47. if 'default' in kwargs:
  48. self.default, error = self.check_data_value(kwargs['default'])
  49. if error:
  50. raise error
  51. del(kwargs['default'])
  52. for argname, argval in kwargs.items():
  53. setattr(self, argname, argval)
  54. ## Fieldtype name
  55. @classmethod
  56. def name(cls):
  57. return cls.__module__.split('.')[-1]
  58. @classmethod
  59. def is_reference(cls):
  60. return issubclass(cls, Reference)
  61. @classmethod
  62. def is_singlereference(cls):
  63. return issubclass(cls, SingleRef)
  64. def is_primary_key(self):
  65. return self.primary_key
  66. ##@brief checks if a fieldtype is internal
  67. # @return bool
  68. def is_internal(self):
  69. return self.internal is not False
  70. ##brief check if a value can be nullable
  71. #@param value *
  72. #@throw DataNoneValid if value is None and nullable. LodelExceptions if not nullable
  73. #@return value (if not None)
  74. # @return value
  75. def _check_data_value(self, value):
  76. if value is None:
  77. if not self.nullable:
  78. raise LodelExceptions("None value is forbidden for this data field")
  79. raise DataNoneValid("None with a nullable. This exeption is allowed")
  80. return value
  81. ##@brief calls the data_field (defined in derived class) _check_data_value() method
  82. #@param value *
  83. #@return tuple (value|None, None|error) value can be cast if NoneError
  84. def check_data_value(self, value):
  85. try:
  86. value = self._check_data_value(value)
  87. except DataNoneValid as expt:
  88. return value, None
  89. except (LodelExceptions, FieldValidationError) as expt:
  90. return None, expt
  91. return value, None
  92. ##@brief checks if this class can override the given data handler
  93. # @param data_handler DataHandler
  94. # @return bool
  95. def can_override(self, data_handler):
  96. if data_handler.__class__.base_type != self.__class__.base_type:
  97. return False
  98. return True
  99. ##@brief Build field value
  100. #@ingroup lodel2_dh_checks
  101. #@warning DO NOT REIMPLEMENT THIS METHOD IN A CUSTOM DATAHANDLER (see
  102. #@ref _construct_data() and @ref lodel2_dh_check_impl )
  103. #@param emcomponent EmComponent : An EmComponent child class instance
  104. #@param fname str : The field name
  105. #@param datas dict : dict storing fields values (from the component)
  106. #@param cur_value : the value from the current field (identified by fieldname)
  107. #@return the value
  108. #@throw RunTimeError if data construction fails
  109. #@todo raise something else
  110. def construct_data(self, emcomponent, fname, datas, cur_value):
  111. emcomponent_fields = emcomponent.fields()
  112. data_handler = None
  113. if fname in emcomponent_fields:
  114. data_handler = emcomponent_fields[fname]
  115. new_val = cur_value
  116. if fname in datas.keys():
  117. pass
  118. elif data_handler is not None and hasattr(data_handler, 'default'):
  119. new_val = data_handler.default
  120. elif data_handler is not None and data_handler.nullable:
  121. new_val = None
  122. return self._construct_data(emcomponent, fname, datas, new_val)
  123. ##@brief Designed to be reimplemented by child classes
  124. #@param emcomponent EmComponent : An EmComponent child class instance
  125. #@param fname str : The field name
  126. #@param datas dict : dict storing fields values (from the component)
  127. #@param cur_value : the value from the current field (identified by fieldname)
  128. #@return the value
  129. #@see construct_data() lodel2_dh_check_impl
  130. def _construct_data(self, emcomponent, fname, datas, cur_value):
  131. return cur_value
  132. ##@brief Check datas consistency
  133. #@ingroup lodel2_dh_checks
  134. #@warning DO NOT REIMPLEMENT THIS METHOD IN A CUSTOM DATAHANDLER (see
  135. #@ref _construct_data() and @ref lodel2_dh_check_impl )
  136. #@warning the datas argument looks like a dict but is not a dict
  137. #see @ref base_classes.DatasConstructor "DatasConstructor" and
  138. #@ref lodel2_dh_datas_construction "Datas construction section"
  139. #@param emcomponent EmComponent : An EmComponent child class instance
  140. #@param fname : the field name
  141. #@param datas dict : dict storing fields values
  142. #@return an Exception instance if fails else True
  143. #@todo A implémenter
  144. def check_data_consistency(self, emcomponent, fname, datas):
  145. return self._check_data_consistency(emcomponent, fname, datas)
  146. ##@brief Designed to be reimplemented by child classes
  147. #@param emcomponent EmComponent : An EmComponent child class instance
  148. #@param fname : the field name
  149. #@param datas dict : dict storing fields values
  150. #@return an Exception instance if fails else True
  151. #@see check_data_consistency() lodel2_dh_check_impl
  152. def _check_data_consistency(self, emcomponent, fname, datas):
  153. return True
  154. ##@brief make consistency after a query
  155. # @param emcomponent EmComponent : An EmComponent child class instance
  156. # @param fname : the field name
  157. # @param datas dict : dict storing fields values
  158. # @return an Exception instance if fails else True
  159. # @todo A implémenter
  160. def make_consistency(self, emcomponent, fname, datas):
  161. pass
  162. ##@brief This method is use by plugins to register new data handlers
  163. @classmethod
  164. def register_new_handler(cls, name, data_handler):
  165. if not inspect.isclass(data_handler):
  166. raise ValueError("A class was expected but %s given" % type(data_handler))
  167. if not issubclass(data_handler, DataHandler):
  168. raise ValueError("A data handler HAS TO be a child class of DataHandler")
  169. cls.__custom_handlers[name] = data_handler
  170. ##@brief Load all datahandlers
  171. @classmethod
  172. def load_base_handlers(cls):
  173. if cls._base_handlers is None:
  174. cls._base_handlers = dict()
  175. for module_name in cls._HANDLERS_MODULES:
  176. module = importlib.import_module('lodel.leapi.datahandlers.%s' % module_name)
  177. for name, obj in inspect.getmembers(module):
  178. if inspect.isclass(obj):
  179. logger.debug("Load data handler %s.%s" % (obj.__module__, obj.__name__))
  180. cls._base_handlers[name.lower()] = obj
  181. return copy.copy(cls._base_handlers)
  182. ##@brief given a field type name, returns the associated python class
  183. # @param fieldtype_name str : A field type name (not case sensitive)
  184. # @return DataField child class
  185. # @note To access custom data handlers it can be cool to prefix the handler name by plugin name for example ? (to ensure name unicity)
  186. @classmethod
  187. def from_name(cls, fieldtype_name):
  188. cls.load_base_handlers()
  189. all_handlers = dict(cls._base_handlers, **cls.__custom_handlers)
  190. fieldtype_name = fieldtype_name.lower()
  191. if fieldtype_name not in all_handlers:
  192. raise NameError("No data handlers named '%s'" % (fieldtype_name,))
  193. return all_handlers[fieldtype_name]
  194. ##@brief Return the module name to import in order to use the datahandler
  195. # @param data_handler_name str : Data handler name
  196. # @return a str
  197. @classmethod
  198. def module_name(cls, data_handler_name):
  199. data_handler_name = data_handler_name.lower()
  200. handler_class = cls.from_name(data_handler_name)
  201. return '{module_name}.{class_name}'.format(
  202. module_name=handler_class.__module__,
  203. class_name=handler_class.__name__
  204. )
  205. ##@brief __hash__ implementation for fieldtypes
  206. def __hash__(self):
  207. hash_dats = [self.__class__.__module__]
  208. for kdic in sorted([k for k in self.__dict__.keys() if not k.startswith('_')]):
  209. hash_dats.append((kdic, getattr(self, kdic)))
  210. return hash(tuple(hash_dats))
  211. ##@brief Base class for datas data handler (by opposition with references)
  212. #@ingroup lodel2_datahandlers
  213. class DataField(DataHandler):
  214. pass
  215. ##@brief Abstract class for all references
  216. #@ingroup lodel2_datahandlers
  217. #
  218. # References are fields that stores a reference to another
  219. # editorial object
  220. #@todo Construct data implementation : transform the data into a LeObject
  221. #instance
  222. #@todo Check data consistency implementation : check that LeObject instance
  223. #is from an allowed class
  224. class Reference(DataHandler):
  225. base_type = "ref"
  226. ##@brief Instanciation
  227. # @param allowed_classes list | None : list of allowed em classes if None no restriction
  228. # @param back_reference tuple | None : tuple containing (LeObject child class, fieldname)
  229. # @param internal bool : if False, the field is not internal
  230. # @param **kwargs : other arguments
  231. def __init__(self, allowed_classes=None, back_reference=None, internal=False, **kwargs):
  232. self.__allowed_classes = set() if allowed_classes is None else set(allowed_classes)
  233. self.allowed_classes = list() if allowed_classes is None else allowed_classes
  234. if back_reference is not None:
  235. if len(back_reference) != 2:
  236. raise ValueError("A tuple (classname, fieldname) expected but got '%s'" % back_reference)
  237. #if not issubclass(lodel.leapi.leobject.LeObject, back_reference[0]) or not isinstance(back_reference[1], str):
  238. # raise TypeError("Back reference was expected to be a tuple(<class LeObject>, str) but got : (%s, %s)" % (back_reference[0], back_reference[1]))
  239. self.__back_reference = back_reference
  240. super().__init__(internal=internal, **kwargs)
  241. ##@brief Method designed to return an empty value for this kind of
  242. #multipleref
  243. @classmethod
  244. def empty(cls):
  245. return None
  246. ##@brief Property that takes value of a copy of the back_reference tuple
  247. @property
  248. def back_reference(self):
  249. return copy.copy(self.__back_reference)
  250. ##@brief Property that takes value of datahandler of the backreference or
  251. #None
  252. @property
  253. def back_ref_datahandler(self):
  254. if self.__back_reference is None:
  255. return None
  256. return self.__back_reference[0].data_handler(self.__back_reference[1])
  257. @property
  258. def linked_classes(self):
  259. return copy.copy(self.__allowed_classes)
  260. ##@brief Set the back reference for this field.
  261. def _set_back_reference(self, back_reference):
  262. self.__back_reference = back_reference
  263. ##@brief Check and cast value in appropriate type
  264. #@param value *
  265. #@throw FieldValidationError if value is an appropriate type
  266. #@return value
  267. #@todo implement the check when we have LeObject uid check value
  268. def _check_data_value(self, value):
  269. from lodel.leapi.leobject import LeObject
  270. value = super()._check_data_value(value)
  271. if not (hasattr(value, '__class__') and
  272. issubclass(value.__class__, LeObject)):
  273. if self.__allowed_classes:
  274. rcls = list(self.__allowed_classes)[0]
  275. uidname = rcls.uid_fieldname()[0]# TODO multiple uid is broken
  276. uiddh = rcls.data_handler(uidname)
  277. value = uiddh._check_data_value(value)
  278. else:
  279. raise FieldValidationError("Reference datahandler can not check this value %s if any allowed_class is allowed." % value)
  280. return value
  281. ##@brief Check datas consistency
  282. #@param emcomponent EmComponent : An EmComponent child class instance
  283. #@param fname : the field name
  284. #@param datas dict : dict storing fields values
  285. #@return an Exception instance if fails else True
  286. #@todo check for performance issue and check logics
  287. #@todo Implements consistency checking on value : Check that the given value
  288. #points onto an allowed class
  289. #@warning composed uid capabilities broken here
  290. def check_data_consistency(self, emcomponent, fname, datas):
  291. rep = super().check_data_consistency(emcomponent, fname, datas)
  292. if isinstance(rep, Exception):
  293. return rep
  294. if self.back_reference is None:
  295. return True
  296. # !! Reimplement instance fetching in construct data !!
  297. target_class = self.back_reference[0]
  298. target_uidfield = target_class.uid_fieldname()[0] #multi uid broken here
  299. value = datas[fname]
  300. obj = target_class.get([(target_uidfield, '=', value)])
  301. if len(obj) == 0:
  302. logger.warning('Object referenced does not exist')
  303. return False
  304. return True
  305. ##@brief Utility method designed to fetch referenced objects
  306. #@param value mixed : the field value
  307. #@throw NotImplementedError
  308. def get_referenced(self, value):
  309. raise NotImplementedError
  310. ##@brief This class represent a data_handler for single reference to another object
  311. #
  312. # The fields using this data handlers are like "foreign key" on another object
  313. class SingleRef(Reference):
  314. def __init__(self, allowed_classes=None, **kwargs):
  315. super().__init__(allowed_classes=allowed_classes, **kwargs)
  316. ##@brief Check and cast value in appropriate type
  317. #@param value: *
  318. #@throw FieldValidationError if value is unappropriate or can not be cast
  319. #@return value
  320. def _check_data_value(self, value):
  321. value = super()._check_data_value(value)
  322. logger.warning("A vérifier..provisoire pour les tests")
  323. #if (expt is None and (len(val)>1)):
  324. # raise FieldValidationError("List or string expected for a set field")
  325. return value
  326. ##@brief Utility method designed to fetch referenced objects
  327. #@param value mixed : the field value
  328. #@return A LeObject child class instance
  329. #@throw LodelDataHandlerConsistencyException if no referenced object found
  330. def get_referenced(self, value):
  331. for leo_cls in self.linked_classes:
  332. res = leo_cls.get_from_uid(value)
  333. if res is not None:
  334. return res
  335. raise LodelDataHandlerConsistencyException("Unable to find \
  336. referenced object with uid %s" % value)
  337. ##@brief This class represent a data_handler for multiple references to another object
  338. #@ingroup lodel2_datahandlers
  339. #
  340. # The fields using this data handlers are like SingleRef but can store multiple references in one field
  341. # @note for the moment split on ',' chars
  342. class MultipleRef(Reference):
  343. ##
  344. # @param max_item int | None : indicate the maximum number of item referenced by this field, None mean no limit
  345. # @param kwargs dict
  346. def __init__(self, max_item=None, **kwargs):
  347. self.max_item = max_item
  348. super().__init__(**kwargs)
  349. ##@brief Method designed to return an empty value for this kind of
  350. #multipleref
  351. @classmethod
  352. def empty(cls):
  353. return []
  354. ##@brief Check and cast value in appropriate type
  355. #@param value *
  356. #@throw FieldValidationError if value is unappropriate or can not be cast
  357. #@return value
  358. #@TODO Writing test error for errors when stored multiple references in one field
  359. def _check_data_value(self, value):
  360. value = DataHandler._check_data_value(self, value)
  361. if not hasattr(value, '__iter__'):
  362. raise FieldValidationError("MultipleRef has to be an iterable or a string, '%s' found" % value)
  363. if self.max_item is not None:
  364. if self.max_item < len(value):
  365. raise FieldValidationError("Too many items")
  366. new_val = list()
  367. error_list = list()
  368. for i, v in enumerate(value):
  369. try:
  370. v = super()._check_data_value(v)
  371. new_val.append(v)
  372. except (FieldValidationError):
  373. error_list.append(repr(v))
  374. if len(error_list) > 0:
  375. raise FieldValidationError("MultipleRef have for invalid values [%s] :" % (",".join(error_list)))
  376. return new_val
  377. ##@brief Utility method designed to fetch referenced objects
  378. #@param values mixed : the field value
  379. #@return A list of LeObject child class instance
  380. #@throw LodelDataHandlerConsistencyException if some referenced objects
  381. #were not found
  382. def get_referenced(self, values):
  383. if values is None or len(values) == 0:
  384. return list()
  385. left = set(values)
  386. values = set(values)
  387. res = list()
  388. for leo_cls in self.linked_classes:
  389. uidname = leo_cls.uid_fieldname()[0] #MULTIPLE UID BROKEN HERE
  390. tmp_res = leo_cls.get(('%s in (%s)' % (uidname, ','.join(
  391. [str(l) for l in left]))))
  392. left ^= set(( leo.uid() for leo in tmp_res))
  393. res += tmp_res
  394. if len(left) == 0:
  395. return res
  396. raise LodelDataHandlerConsistencyException("Unable to find \
  397. some referenced objects. Followinf uid were not found : %s" % ','.join(left))
  398. ## @brief Class designed to handle datas access will fieldtypes are constructing datas
  399. #@ingroup lodel2_datahandlers
  400. #
  401. # This class is designed to allow automatic scheduling of construct_data calls.
  402. #
  403. # In theory it's able to detect circular dependencies
  404. # @todo test circular deps detection
  405. # @todo test circulat deps false positiv
  406. class DatasConstructor(object):
  407. ## @brief Init a DatasConstructor
  408. # @param leobject LeCrud : @ref LeObject child class
  409. # @param datas dict : dict with field name as key and field values as value
  410. # @param fields_handler dict : dict with field name as key and data handler instance as value
  411. def __init__(self, leobject, datas, fields_handler):
  412. ## Stores concerned class
  413. self._leobject = leobject
  414. ## Stores datas and constructed datas
  415. self._datas = copy.copy(datas)
  416. ## Stores fieldtypes
  417. self._fields_handler = fields_handler
  418. ## Stores list of fieldname for constructed datas
  419. self._constructed = []
  420. ## Stores construct calls list
  421. self._construct_calls = []
  422. ## @brief Implements the dict.keys() method on instance
  423. def keys(self):
  424. return self._datas.keys()
  425. ## @brief Allows to access the instance like a dict
  426. def __getitem__(self, fname):
  427. if fname not in self._constructed:
  428. if fname in self._construct_calls:
  429. raise RuntimeError('Probably circular dependencies in fieldtypes')
  430. cur_value = self._datas[fname] if fname in self._datas else None
  431. self._datas[fname] = self._fields_handler[fname].construct_data(self._leobject, fname, self, cur_value)
  432. self._constructed.append(fname)
  433. return self._datas[fname]
  434. ## @brief Allows to set instance values like a dict
  435. # @warning Should not append in theory
  436. def __setitem__(self, fname, value):
  437. self._datas[fname] = value
  438. warnings.warn("Setting value of an DatasConstructor instance")