Ei kuvausta
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.

leobject.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. #-*- coding: utf-8 -*-
  2. import importlib
  3. class LeApiErrors(Exception):
  4. ##@brief Instanciate a new exceptions handling multiple exceptions
  5. # @param msg str : Exception message
  6. # @param exceptions dict : A list of data check Exception with concerned field (or stuff) as key
  7. def __init__(self, msg = "Unknow error", exceptions = None):
  8. self._msg = msg
  9. self._exceptions = dict() if exceptions is None else exceptions
  10. def __repr__(self):
  11. return self.__str__()
  12. def __str__(self):
  13. msg = self._msg
  14. for_iter = self._exceptions.items() if isinstance(self._exceptions, dict) else enumerate(self.__exceptions)
  15. for obj, expt in for_iter:
  16. msg += "\n\t{expt_obj} : ({expt_name}) {expt_msg}; ".format(
  17. expt_obj = obj,
  18. expt_name=expt.__class__.__name__,
  19. expt_msg=str(expt)
  20. )
  21. return msg
  22. ##@brief When an error concern a query
  23. class LeApiQueryError(LeApiErrors):
  24. pass
  25. ##@brief When an error concerns a datas
  26. class LeApiDataCheckError(LeApiErrors):
  27. pass
  28. ##@brief Wrapper class for LeObject getter & setter
  29. #
  30. # This class intend to provide easy & friendly access to LeObject fields values
  31. # without name collision problems
  32. # @note Wrapped methods are : LeObject.data() & LeObject.set_data()
  33. class LeObjectValues(object):
  34. ##@brief Construct a new LeObjectValues
  35. # @param set_callback method : The LeObject.set_datas() method of corresponding LeObject class
  36. # @param get_callback method : The LeObject.get_datas() method of corresponding LeObject class
  37. def __init__(self, fieldnames_callback, set_callback, get_callback):
  38. self.__setter = set_callback
  39. self.__getter = get_callback
  40. ##@brief Provide read access to datas values
  41. # @note Read access should be provided for all fields
  42. # @param fname str : Field name
  43. def __getattribute__(self, fname):
  44. return self.__getter(fname)
  45. ##@brief Provide write access to datas values
  46. # @note Write acces shouldn't be provided for internal or immutable fields
  47. # @param fname str : Field name
  48. # @param fval * : the field value
  49. def __setattribute__(self, fname, fval):
  50. return self.__setter(fname, fval)
  51. class LeObject(object):
  52. ##@brief boolean that tells if an object is abtract or not
  53. _abstract = None
  54. ##@brief A dict that stores DataHandler instances indexed by field name
  55. _fields = None
  56. ##@brief A tuple of fieldname (or a uniq fieldname) representing uid
  57. _uid = None
  58. ##@brief Construct an object representing an Editorial component
  59. # @note Can be considered as EmClass instance
  60. def __init__(self, **kwargs):
  61. if self._abstract:
  62. raise NotImplementedError("%s is abstract, you cannot instanciate it." % self.__class__.__name__ )
  63. ##@brief A dict that stores fieldvalues indexed by fieldname
  64. self.__datas = { fname:None for fname in self._fields }
  65. ##@brief Store a list of initianilized fields when instanciation not complete else store True
  66. self.__initialized = list()
  67. ##@brief Datas accessor. Instance of @ref LeObjectValues
  68. self.d = LeObjectValues(self.fieldnames, self.set_data, self.data)
  69. # Checks that uid is given
  70. for uid_name in self._uid:
  71. if uid_name not in kwargs:
  72. raise AttributeError("Cannot instanciate a LeObject without it's identifier")
  73. self.__datas[uid_name] = kwargs[uid_name]
  74. del(kwargs[uid_name])
  75. self.__initialized.append(uid_name)
  76. # Processing given fields
  77. allowed_fieldnames = self.fieldnames(include_ro = False)
  78. err_list = list()
  79. for fieldname, fieldval in kwargs.items():
  80. if fieldname not in allowed_fieldnames:
  81. if fieldname in self._fields:
  82. err_list.append(
  83. AttributeError("Value given for internal field : '%s'" % fieldname)
  84. )
  85. else:
  86. err_list.append(
  87. AttributeError("Unknown fieldname : '%s'" % fieldname)
  88. )
  89. else:
  90. self.__datas[fieldame] = fieldval
  91. self.__initialized = list()
  92. self.set_initialized()
  93. #-----------------------------------#
  94. # Fields datas handling methods #
  95. #-----------------------------------#
  96. ##@brief @property True if LeObject is initialized else False
  97. @property
  98. def initialized(self):
  99. return not isinstance(self.__initialized, list)
  100. ##@brief Return a list of fieldnames
  101. # @param include_ro bool : if True include read only field names
  102. # @return a list of str
  103. @classmethod
  104. def fieldnames(cls, include_ro = False):
  105. if not include_ro:
  106. return [ fname for fname in self._fields if not self._fields[fname].is_internal() ]
  107. else:
  108. return list(self._fields.keys())
  109. @classmethod
  110. def name2objname(cls, name):
  111. return name.title()
  112. ##@brief Return the datahandler asssociated with a LeObject field
  113. # @param fieldname str : The fieldname
  114. # @return A data handler instance
  115. @classmethod
  116. def data_handler(cls, fieldname):
  117. if not fieldname in cls._fields:
  118. raise NameError("No field named '%s' in %s" % (fieldname, cls.__name__))
  119. return cls._fields[fieldname]
  120. ##@brief Return a LeObject child class from a name
  121. # @warning This method has to be called from dynamically generated LeObjects
  122. # @param leobject_name str : LeObject name
  123. # @return A LeObject child class
  124. # @throw NameError if invalid name given
  125. @classmethod
  126. def name2class(cls, leobject_name):
  127. if cls.__module__ == 'lodel.leapi.leobject':
  128. raise NotImplementedError("Abstract method")
  129. mod = importlib.import_module(cls.__module__)
  130. try:
  131. return getattr(mod, leobject_name)
  132. except AttributeError:
  133. raise NameError("No LeObject named '%s'" % leobject_name)
  134. @classmethod
  135. def is_abstract(cls):
  136. return cls._abstract
  137. ##@brief Read only access to all datas
  138. # @note for fancy data accessor use @ref LeObject.g attribute @ref LeObjectValues instance
  139. # @param name str : field name
  140. # @return the Value
  141. # @throw RuntimeError if the field is not initialized yet
  142. # @throw NameError if name is not an existing field name
  143. def data(self, field_name):
  144. if field_name not in self._fields.keys():
  145. raise NameError("No such field in %s : %s" % (self.__class__.__name__, name))
  146. if not self.initialized and name not in self.__initialized:
  147. raise RuntimeError("The field %s is not initialized yet (and have no value)" % name)
  148. return self.__datas[name]
  149. ##@brief Datas setter
  150. # @note for fancy data accessor use @ref LeObject.g attribute @ref LeObjectValues instance
  151. # @param fname str : field name
  152. # @param fval * : field value
  153. # @return the value that is really set
  154. # @throw NameError if fname is not valid
  155. # @throw AttributeError if the field is not writtable
  156. def set_data(self, fname, fval):
  157. if field_name not in self.fieldnames(include_ro = False):
  158. if field_name not in self._fields.keys():
  159. raise NameError("No such field in %s : %s" % (self.__class__.__name__, name))
  160. else:
  161. raise AttributeError("The field %s is read only" % fname)
  162. self.__datas[fname] = fval
  163. if not self.initialized and fname not in self.__initialized:
  164. # Add field to initialized fields list
  165. self.__initialized.append(fname)
  166. self.__set_initialized()
  167. if self.initialized:
  168. # Running full value check
  169. ret = self.__check_modified_values()
  170. if ret is None:
  171. return self.__datas[fname]
  172. else:
  173. raise LeApiErrors("Data check error", ret)
  174. else:
  175. # Doing value check on modified field
  176. # We skip full validation here because the LeObject is not fully initialized yet
  177. val, err = self._fields[fname].check_data_value(fval)
  178. if isinstance(err, Exception):
  179. #Revert change to be in valid state
  180. del(self.__datas[fname])
  181. del(self.__initialized[-1])
  182. raise LeApiErrors("Data check error", {fname:err})
  183. else:
  184. self.__datas[fname] = val
  185. ##@brief Update the __initialized attribute according to LeObject internal state
  186. #
  187. # Check the list of initialized fields and set __initialized to True if all fields initialized
  188. def __set_initialized(self):
  189. if isinstance(self.__initialized, list):
  190. expected_fields = self.fieldnames(include_ro = False) + self._uid
  191. if set(expected_fields) == set(self.__initialized):
  192. self.__initialized = True
  193. ##@brief Designed to be called when datas are modified
  194. #
  195. # Make different checks on the LeObject given it's state (fully initialized or not)
  196. # @return None if checks succeded else return an exception list
  197. def __check_modified_values(self):
  198. err_list = dict()
  199. if self.__initialized is True:
  200. # Data value check
  201. for fname in self.fieldnames(include_ro = False):
  202. val, err = self._fields[fname].check_data_value(self.__datas[fname])
  203. if err is not None:
  204. err_list[fname] = err
  205. else:
  206. self.__datas[fname] = val
  207. # Data construction
  208. if len(err_list) == 0:
  209. for fname in self.fieldnames(include_ro = True):
  210. try:
  211. field = self._fields[fname]
  212. self.__datas[fname] = fields.construct_data( self,
  213. fname,
  214. self.__datas,
  215. self.__datas[fname]
  216. )
  217. except Exception as e:
  218. err_list[fname] = e
  219. # Datas consistency check
  220. if len(err_list) == 0:
  221. for fname in self.fieldnames(include_ro = True):
  222. field = self._fields[fname]
  223. ret = field.check_data_consistency(self, fname, self.__datas)
  224. if isinstance(ret, Exception):
  225. err_list[fname] = ret
  226. else:
  227. # Data value check for initialized datas
  228. for fname in self.__initialized:
  229. val, err = self._fields[fname].check_data_value(self.__datas[fname])
  230. if err is not None:
  231. err_list[fname] = err
  232. else:
  233. self.__datas[fname] = val
  234. return err_list if len(err_list) > 0 else None
  235. #--------------------#
  236. # Other methods #
  237. #--------------------#
  238. ##@brief Temporary method to set private fields attribute at dynamic code generation
  239. #
  240. # This method is used in the generated dynamic code to set the _fields attribute
  241. # at the end of the dyncode parse
  242. # @warning This method is deleted once the dynamic code loaded
  243. # @param field_list list : list of EmField instance
  244. # @param cls
  245. @classmethod
  246. def _set__fields(cls, field_list):
  247. cls._fields = field_list
  248. ## @brief Check that datas are valid for this type
  249. # @param datas dict : key == field name value are field values
  250. # @param complete bool : if True expect that datas provide values for all non internal fields
  251. # @param allow_internal bool : if True don't raise an error if a field is internal
  252. # @param cls
  253. # @return Checked datas
  254. # @throw LeApiDataCheckError if errors reported during check
  255. @classmethod
  256. def check_datas_value(cls, datas, complete = False, allow_internal = True):
  257. err_l = dict() #Error storing
  258. correct = set() #valid fields name
  259. mandatory = set() #mandatory fields name
  260. for fname, datahandler in cls._fields.items():
  261. if allow_internal or not datahandler.is_internal():
  262. correct.add(fname)
  263. if complete and not hasattr(datahandler, 'default'):
  264. mandatory.add(fname)
  265. provided = set(datas.keys())
  266. # searching for unknow fields
  267. for u_f in provided - correct:
  268. #Here we can check if the field is invalid or rejected because
  269. # it is internel
  270. err_l[u_f] = AttributeError("Unknown or unauthorized field '%s'" % u_f)
  271. # searching for missing mandatory fieldsa
  272. for missing in mandatory - provided:
  273. err_l[miss_field] = AttributeError("The data for field '%s' is missing" % missing)
  274. #Checks datas
  275. checked_datas = dict()
  276. for name, value in [ (name, value) for name, value in datas.items() if name in correct ]:
  277. dh = cls._fields[name]
  278. res = dh.check_data_value(value)
  279. checked_datas[name], err = res
  280. if err:
  281. err_l[name] = err
  282. if len(err_l) > 0:
  283. raise LeApiDataCheckError("Error while checking datas", err_l)
  284. return checked_datas
  285. ##@brief Check and prepare datas
  286. #
  287. # @warning when complete = False we are not able to make construct_datas() and _check_data_consistency()
  288. #
  289. # @param datas dict : {fieldname : fieldvalue, ...}
  290. # @param complete bool : If True you MUST give all the datas
  291. # @param allow_internal : Wether or not interal fields are expected in datas
  292. # @param cls
  293. # @return Datas ready for use
  294. # @todo: complete is very unsafe, find a way to get rid of it
  295. @classmethod
  296. def prepare_datas(cls, datas, complete=False, allow_internal=True):
  297. if not complete:
  298. warnings.warn("\nActual implementation can make datas construction and consitency unsafe when datas are not complete\n")
  299. ret_datas = cls.check_datas_value(datas, complete, allow_internal)
  300. if isinstance(ret_datas, Exception):
  301. raise ret_datas
  302. if complete:
  303. ret_datas = cls._construct_datas(ret_datas)
  304. cls._check_datas_consistency(ret_datas)
  305. return ret_datas
  306. ## @brief Construct datas values
  307. #
  308. # @param cls
  309. # @param datas dict : Datas that have been returned by LeCrud.check_datas_value() methods
  310. # @return A new dict of datas
  311. # @todo IMPLEMENTATION
  312. @classmethod
  313. def _construct_datas(cls, datas):
  314. """
  315. constructor = DatasConstructor(cls, datas, cls.fieldtypes())
  316. ret = {
  317. fname:constructor[fname]
  318. for fname, ftype in cls.fieldtypes().items()
  319. if not ftype.is_internal() or ftype.internal != 'autosql'
  320. }
  321. return ret
  322. """
  323. pass
  324. ## @brief Check datas consistency
  325. # @warning assert that datas is complete
  326. # @param cls
  327. # @param datas dict : Datas that have been returned by LeCrud._construct_datas() method
  328. # @throw LeApiDataCheckError if fails
  329. @classmethod
  330. def _check_datas_consistency(cls, datas):
  331. err_l = []
  332. err_l = dict()
  333. for fname, dh in cls._fields.items():
  334. ret = dh.check_data_consistency(cls, fname, datas)
  335. if isinstance(ret, Exception):
  336. err_l[fname] = ret
  337. if len(err_l) > 0:
  338. raise LeApiDataCheckError("Datas consistency checks fails", err_l)