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

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