Nessuna descrizione
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 22KB

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