No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base_classes.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 import logger
  10. class FieldValidationError(Exception):
  11. pass
  12. ##@brief Base class for all data handlers
  13. #@ingroup lodel2_datahandlers
  14. class DataHandler(object):
  15. _HANDLERS_MODULES = ('datas_base', 'datas', 'references')
  16. ##@brief Stores the DataHandler childs classes indexed by name
  17. _base_handlers = None
  18. ##@brief Stores custom datahandlers classes indexed by name
  19. # @todo do it ! (like plugins, register handlers... blablabla)
  20. __custom_handlers = dict()
  21. help_text = 'Generic Field Data Handler'
  22. ##@brief List fields that will be exposed to the construct_data_method
  23. _construct_datas_deps = []
  24. ##@brief constructor
  25. # @param internal False | str : define whether or not a field is internal
  26. # @param immutable bool : indicates if the fieldtype has to be defined in child classes of LeObject or if it is
  27. # designed globally and immutable
  28. # @param **args
  29. # @throw NotImplementedError if it is instanciated directly
  30. def __init__(self, **kwargs):
  31. if self.__class__ == DataHandler:
  32. raise NotImplementedError("Abstract class")
  33. self.__arguments = kwargs
  34. self.nullable = True
  35. self.uniq = False
  36. self.immutable = False
  37. self.primary_key = False
  38. self.internal = False
  39. if 'default' in kwargs:
  40. self.default, error = self.check_data_value(kwargs['default'])
  41. if error:
  42. raise error
  43. del(kwargs['default'])
  44. for argname, argval in kwargs.items():
  45. setattr(self, argname, argval)
  46. ## Fieldtype name
  47. @classmethod
  48. def name(cls):
  49. return cls.__module__.split('.')[-1]
  50. @classmethod
  51. def is_reference(cls):
  52. return issubclass(cls, Reference)
  53. def is_primary_key(self):
  54. return self.primary_key
  55. ##@brief checks if a fieldtype is internal
  56. # @return bool
  57. def is_internal(self):
  58. return self.internal is not False
  59. ##@brief calls the data_field defined _check_data_value() method
  60. #@ingroup lodel2_dh_checks
  61. #@warning DO NOT REIMPLEMENT THIS METHOD IN A CUSTOM DATAHANDLER (see
  62. #@ref _construct_data() and @ref lodel2_dh_check_impl )
  63. #@return tuple (value, error|None)
  64. def check_data_value(self, value):
  65. if value is None:
  66. if not self.nullable:
  67. return None, TypeError("'None' value but field is not nullable")
  68. return None, None
  69. return self._check_data_value(value)
  70. ##@brief Designed to be implemented in child classes
  71. def _check_data_value(self, value):
  72. return value, None
  73. ##@brief checks if this class can override the given data handler
  74. # @param data_handler DataHandler
  75. # @return bool
  76. def can_override(self, data_handler):
  77. if data_handler.__class__.base_type != self.__class__.base_type:
  78. return False
  79. return True
  80. ##@brief Build field value
  81. #@ingroup lodel2_dh_checks
  82. #@warning DO NOT REIMPLEMENT THIS METHOD IN A CUSTOM DATAHANDLER (see
  83. #@ref _construct_data() and @ref lodel2_dh_check_impl )
  84. #@param emcomponent EmComponent : An EmComponent child class instance
  85. #@param fname str : The field name
  86. #@param datas dict : dict storing fields values (from the component)
  87. #@param cur_value : the value from the current field (identified by fieldname)
  88. #@return the value
  89. #@throw RunTimeError if data construction fails
  90. #@todo raise something else
  91. def construct_data(self, emcomponent, fname, datas, cur_value):
  92. emcomponent_fields = emcomponent.fields()
  93. data_handler = None
  94. if fname in emcomponent_fields:
  95. data_handler = emcomponent_fields[fname]
  96. new_val = cur_value
  97. if fname in datas.keys():
  98. pass
  99. elif data_handler is not None and hasattr(data_handler, 'default'):
  100. new_val = data_handler.default
  101. elif data_handler is not None and data_handler.nullable:
  102. new_val = None
  103. return self._construct_data(emcomponent, fname, datas, new_val)
  104. ##@brief Designed to be reimplemented by child classes
  105. #@param emcomponent EmComponent : An EmComponent child class instance
  106. #@param fname str : The field name
  107. #@param datas dict : dict storing fields values (from the component)
  108. #@param cur_value : the value from the current field (identified by fieldname)
  109. #@return the value
  110. #@see construct_data() lodel2_dh_check_impl
  111. def _construct_data(self, empcomponent, fname, datas, cur_value):
  112. return cur_value
  113. ##@brief Check datas consistency
  114. #@ingroup lodel2_dh_checks
  115. #@warning DO NOT REIMPLEMENT THIS METHOD IN A CUSTOM DATAHANDLER (see
  116. #@ref _construct_data() and @ref lodel2_dh_check_impl )
  117. #@warning the datas argument looks like a dict but is not a dict
  118. #see @ref base_classes.DatasConstructor "DatasConstructor" and
  119. #@ref lodel2_dh_datas_construction "Datas construction section"
  120. #@param emcomponent EmComponent : An EmComponent child class instance
  121. #@param fname : the field name
  122. #@param datas dict : dict storing fields values
  123. #@return an Exception instance if fails else True
  124. #@todo A implémenter
  125. def check_data_consistency(self, emcomponent, fname, datas):
  126. return self._check_data_consistency(emcomponent, fname, datas)
  127. ##@brief Designed to be reimplemented by child classes
  128. #@param emcomponent EmComponent : An EmComponent child class instance
  129. #@param fname : the field name
  130. #@param datas dict : dict storing fields values
  131. #@return an Exception instance if fails else True
  132. #@see check_data_consistency() lodel2_dh_check_impl
  133. def _check_data_consistency(self, emcomponent, fname, datas):
  134. return True
  135. ##@brief make consistency after a query
  136. # @param emcomponent EmComponent : An EmComponent child class instance
  137. # @param fname : the field name
  138. # @param datas dict : dict storing fields values
  139. # @return an Exception instance if fails else True
  140. # @todo A implémenter
  141. def make_consistency(self, emcomponent, fname, datas):
  142. pass
  143. ##@brief This method is use by plugins to register new data handlers
  144. @classmethod
  145. def register_new_handler(cls, name, data_handler):
  146. if not inspect.isclass(data_handler):
  147. raise ValueError("A class was expected but %s given" % type(data_handler))
  148. if not issubclass(data_handler, DataHandler):
  149. raise ValueError("A data handler HAS TO be a child class of DataHandler")
  150. cls.__custom_handlers[name] = data_handler
  151. ##@brief Load all datahandlers
  152. @classmethod
  153. def load_base_handlers(cls):
  154. if cls._base_handlers is None:
  155. cls._base_handlers = dict()
  156. for module_name in cls._HANDLERS_MODULES:
  157. module = importlib.import_module('lodel.leapi.datahandlers.%s' % module_name)
  158. for name, obj in inspect.getmembers(module):
  159. if inspect.isclass(obj):
  160. logger.debug("Load data handler %s.%s" % (obj.__module__, obj.__name__))
  161. cls._base_handlers[name.lower()] = obj
  162. return copy.copy(cls._base_handlers)
  163. ##@brief given a field type name, returns the associated python class
  164. # @param fieldtype_name str : A field type name (not case sensitive)
  165. # @return DataField child class
  166. # @note To access custom data handlers it can be cool to prefix the handler name by plugin name for example ? (to ensure name unicity)
  167. @classmethod
  168. def from_name(cls, name):
  169. cls.load_base_handlers()
  170. all_handlers = dict(cls._base_handlers, **cls.__custom_handlers)
  171. name = name.lower()
  172. if name not in all_handlers:
  173. raise NameError("No data handlers named '%s'" % (name,))
  174. return all_handlers[name]
  175. ##@brief Return the module name to import in order to use the datahandler
  176. # @param data_handler_name str : Data handler name
  177. # @return a str
  178. @classmethod
  179. def module_name(cls, name):
  180. name = name.lower()
  181. handler_class = cls.from_name(name)
  182. return '{module_name}.{class_name}'.format(
  183. module_name = handler_class.__module__,
  184. class_name = handler_class.__name__
  185. )
  186. ##@brief __hash__ implementation for fieldtypes
  187. def __hash__(self):
  188. hash_dats = [self.__class__.__module__]
  189. for kdic in sorted([k for k in self.__dict__.keys() if not k.startswith('_')]):
  190. hash_dats.append((kdic, getattr(self, kdic)))
  191. return hash(tuple(hash_dats))
  192. ##@brief Base class for datas data handler (by opposition with references)
  193. #@ingroup lodel2_datahandlers
  194. class DataField(DataHandler):
  195. pass
  196. ##@brief Abstract class for all references
  197. #@ingroup lodel2_datahandlers
  198. #
  199. # References are fields that stores a reference to another
  200. # editorial object
  201. #
  202. #
  203. #@todo Check data implementation : check_data = is value an UID or an
  204. #LeObject child instance
  205. #@todo Construct data implementation : transform the data into a LeObject
  206. #instance
  207. #@todo Check data consistency implementation : check that LeObject instance
  208. #is from an allowed class
  209. class Reference(DataHandler):
  210. base_type="ref"
  211. ##@brief Instanciation
  212. # @param allowed_classes list | None : list of allowed em classes if None no restriction
  213. # @param back_reference tuple | None : tuple containing (LeObject child class, fieldname)
  214. # @param internal bool : if False, the field is not internal
  215. # @param **kwargs : other arguments
  216. def __init__(self, allowed_classes = None, back_reference = None, internal=False, **kwargs):
  217. ##@brief set of allowed LeObject child classes
  218. self.__allowed_classes = set() if allowed_classes is None else set(allowed_classes)
  219. ##@brief Stores back references informations
  220. self.__back_reference = None
  221. self.__set_back_reference(back_reference)
  222. super().__init__(internal=internal, **kwargs)
  223. @property
  224. def back_reference(self):
  225. return copy.copy(self.__back_reference)
  226. @property
  227. def linked_classes(self):
  228. return copy.copy(self.__allowed_classes)
  229. ##@brief Set the back reference for this field.
  230. def __set_back_reference(self, back_reference):
  231. if back_reference is None:
  232. return
  233. if len(back_reference) != 2:
  234. raise LodelDataHandlerException("A tuple(LeObjectChild, fieldname) \
  235. expected but got '%s'" % back_reference)
  236. self.__back_reference = back_reference
  237. ##@brief Check value
  238. #@param value *
  239. #@return tuple(value, exception)
  240. #@todo implement the check when we have LeObject to check value
  241. def check_data_value(self, value):
  242. return super().check_data_value(value)
  243. if isinstance(value, lodel.editorial_model.components.EmClass):
  244. value = [value]
  245. for elt in value:
  246. if not issubclass(elt.__class__, EmClass):
  247. return None, FieldValidationError("Some elements of this references are not EmClass instances")
  248. if self.__allowed_classes is not None:
  249. if not isinstance(elt, self.__allowed_classes):
  250. return None, FieldValidationError("Some element of this references are not valids (don't fit with allowed_classes")
  251. return value
  252. ##@brief Check datas consistency
  253. #@param emcomponent EmComponent : An EmComponent child class instance
  254. #@param fname : the field name
  255. #@param datas dict : dict storing fields values
  256. #@return an Exception instance if fails else True
  257. #@todo check for performance issue and check logics
  258. #@todo Implements consistency checking on value : Check that the given value
  259. #points onto an allowed class
  260. #@warning composed uid capabilities broken here
  261. def check_data_consistency(self, emcomponent, fname, datas):
  262. rep = super().check_data_consistency(emcomponent, fname, datas)
  263. if isinstance(rep, Exception):
  264. return rep
  265. if self.back_reference is None:
  266. return True
  267. #Checking back reference consistency
  268. # !! Reimplement instance fetching in construct data !!
  269. dh = emcomponent.field(fname)
  270. uid = datas[emcomponent.uid_fieldname()[0]] #multi uid broken here
  271. target_class = self.back_reference[0]
  272. target_field = self.back_reference[1]
  273. target_uidfield = target_class.uid_fieldname()[0] #multi uid broken here
  274. value = datas[fname]
  275. obj = target_class.get([(target_uidfield , '=', value)])
  276. if len(obj) == 0:
  277. logger.warning('Object referenced does not exist')
  278. return False
  279. return True
  280. ##@brief This class represent a data_handler for single reference to another object
  281. #
  282. # The fields using this data handlers are like "foreign key" on another object
  283. class SingleRef(Reference):
  284. def __init__(self, allowed_classes = None, **kwargs):
  285. super().__init__(allowed_classes = allowed_classes)
  286. def _check_data_value(self, value):
  287. val, expt = super()._check_data_value(value)
  288. if not isinstance(expt, Exception):
  289. if len(val) > 1:
  290. return None, FieldValidationError("Only single values are allowed for SingleRef fields")
  291. return val, expt
  292. ##@brief This class represent a data_handler for multiple references to another object
  293. #@ingroup lodel2_datahandlers
  294. #
  295. # The fields using this data handlers are like SingleRef but can store multiple references in one field
  296. # @note for the moment split on ',' chars
  297. class MultipleRef(Reference):
  298. ##
  299. # @param max_item int | None : indicate the maximum number of item referenced by this field, None mean no limit
  300. def __init__(self, max_item = None, **kwargs):
  301. self.max_item = max_item
  302. super().__init__(**kwargs)
  303. def check_data_value(self, value):
  304. value, expt = super().check_data_value(value)
  305. if expt is not None:
  306. #error in parent
  307. return value, expt
  308. elif value is None:
  309. #none value
  310. return value, expt
  311. expt = None
  312. if isinstance(value, str):
  313. value, expt = super()._check_data_value(value)
  314. elif not hasattr(value, '__iter__'):
  315. return None, FieldValidationError("MultipleRef has to be an iterable or a string, '%s' found" % value)
  316. if self.max_item is not None:
  317. if self.max_item < len(value):
  318. return None, FieldValidationError("Too many items")
  319. return value, expt
  320. def construct_data(self, emcomponent, fname, datas, cur_value):
  321. cur_value = super().construct_data(emcomponent, fname, datas, cur_value)
  322. if cur_value == 'None' or cur_value is None or cur_value == '':
  323. return None
  324. emcomponent_fields = emcomponent.fields()
  325. data_handler = None
  326. if fname in emcomponent_fields:
  327. data_handler = emcomponent_fields[fname]
  328. u_fname = emcomponent.uid_fieldname()
  329. uidtype = emcomponent.field(u_fname[0]) if isinstance(u_fname, list) else emcomponent.field(u_fname)
  330. if isinstance(cur_value, str):
  331. value = cur_value.split(',')
  332. l_value = [uidtype.cast_type(uid) for uid in value]
  333. elif isinstance(cur_value, list):
  334. l_value = list()
  335. for value in cur_value:
  336. if isinstance(value,uidtype.cast_type):
  337. l_value.append(value)
  338. else:
  339. raise ValueError("The items must be of the same type, string or %s" % (emcomponent.__name__))
  340. else:
  341. l_value = None
  342. if l_value is not None:
  343. if self.back_reference is not None:
  344. br_class = self.back_reference[0]
  345. for br_id in l_value:
  346. query_filters = list()
  347. query_filters.append((br_class.uid_fieldname()[0], '=', br_id))
  348. br_obj = br_class.get(query_filters)
  349. if len(br_obj) != 0:
  350. br_list = br_obj[0].data(self.back_reference[1])
  351. if br_list is None:
  352. br_list = list()
  353. if br_id not in br_list:
  354. br_list.append(br_id)
  355. logger.info('The referenced object has to be updated')
  356. return l_value
  357. ## @brief Checks the backreference, updates it if it is not complete
  358. # @param emcomponent EmComponent : An EmComponent child class instance
  359. # @param fname : the field name
  360. # @param datas dict : dict storing fields values
  361. """
  362. def make_consistency(self, emcomponent, fname, datas):
  363. dh = emcomponent.field(fname)
  364. logger.info('Warning : multiple uid capabilities are broken here')
  365. uid = datas[emcomponent.uid_fieldname()[0]]
  366. if self.back_reference is not None:
  367. target_class = self.back_reference[0]
  368. target_field = self.back_reference[1]
  369. target_uidfield = target_class.uid_fieldname()[0]
  370. l_value = datas[fname]
  371. if l_value is not None:
  372. for value in l_value:
  373. query_filters = list()
  374. query_filters.append((target_uidfield , '=', value))
  375. obj = target_class.get(query_filters)
  376. if len(obj) == 0:
  377. logger.warning('Object referenced does not exist')
  378. return False
  379. l_uids_ref = obj[0].data(target_field)
  380. if l_uids_ref is None:
  381. l_uids_ref = list()
  382. if uid not in l_uids_ref:
  383. l_uids_ref.append(uid)
  384. obj[0].set_data(target_field, l_uids_ref)
  385. obj[0].update()
  386. """
  387. ## @brief Class designed to handle datas access will fieldtypes are constructing datas
  388. #@ingroup lodel2_datahandlers
  389. #
  390. # This class is designed to allow automatic scheduling of construct_data calls.
  391. #
  392. # In theory it's able to detect circular dependencies
  393. # @todo test circular deps detection
  394. # @todo test circulat deps false positiv
  395. class DatasConstructor(object):
  396. ## @brief Init a DatasConstructor
  397. # @param lec LeCrud : @ref LeObject child class
  398. # @param datas dict : dict with field name as key and field values as value
  399. # @param fields_handler dict : dict with field name as key and data handler instance as value
  400. def __init__(self, leobject, datas, fields_handler):
  401. ## Stores concerned class
  402. self._leobject = leobject
  403. ## Stores datas and constructed datas
  404. self._datas = copy.copy(datas)
  405. ## Stores fieldtypes
  406. self._fields_handler = fields_handler
  407. ## Stores list of fieldname for constructed datas
  408. self._constructed = []
  409. ## Stores construct calls list
  410. self._construct_calls = []
  411. ## @brief Implements the dict.keys() method on instance
  412. def keys(self):
  413. return self._datas.keys()
  414. ## @brief Allows to access the instance like a dict
  415. def __getitem__(self, fname):
  416. if fname not in self._constructed:
  417. if fname in self._construct_calls:
  418. raise RuntimeError('Probably circular dependencies in fieldtypes')
  419. cur_value = self._datas[fname] if fname in self._datas else None
  420. self._datas[fname] = self._fields_handler[fname].construct_data(self._leobject, fname, self, cur_value)
  421. self._constructed.append(fname)
  422. return self._datas[fname]
  423. ## @brief Allows to set instance values like a dict
  424. # @warning Should not append in theory
  425. def __setitem__(self, fname, value):
  426. self._datas[fname] = value
  427. warnings.warn("Setting value of an DatasConstructor instance")