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

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