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

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