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 21KB

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