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.

leobject.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. #-*- coding: utf-8 -*-
  2. ## @package leobject API to access lodel datas
  3. #
  4. # This package contains abstract classes leobject.leclass.LeClass , leobject.letype.LeType, leobject.leobject._LeObject.
  5. # Those abstract classes are designed to be mother classes of dynamically generated classes ( see leobject.lefactory.LeFactory )
  6. ## @package leobject.leobject
  7. # @brief Abstract class designed to be implemented by LeObject
  8. #
  9. # @note LeObject will be generated by leobject.lefactory.LeFactory
  10. import re
  11. import leobject
  12. import EditorialModel
  13. from EditorialModel.types import EmType
  14. REL_SUP = 0
  15. REL_SUB = 1
  16. ## @brief Main class to handle objects defined by the types of an Editorial Model
  17. class _LeObject(object):
  18. ## @brief The editorial model
  19. _model = None
  20. ## @brief The datasource
  21. _datasource = None
  22. ## @brief maps em uid with LeType or LeClass keys are uid values are LeObject childs classes
  23. _me_uid = dict()
  24. _query_re = None
  25. _query_operators = ['=', '<=', '>=', '!=', '<', '>', ' in ', ' not in ']
  26. ## @brief Instantiate with a Model and a DataSource
  27. # @param **kwargs dict : datas usefull to instanciate a _LeObject
  28. def __init__(self, **kwargs):
  29. raise NotImplementedError("Abstract constructor")
  30. ## @brief Given a ME uid return the corresponding LeClass or LeType class
  31. # @return a LeType or LeClass child class
  32. # @throw KeyError if no corresponding child classes
  33. @classmethod
  34. def uid2leobj(cls, uid):
  35. uid = int(uid)
  36. if uid not in cls._me_uid:
  37. raise KeyError("No LeType or LeClass child classes with uid '%d'"%uid)
  38. return cls._me_uid[uid]
  39. ## @brief Creates new entries in the datasource
  40. # @param datas list : A list a dict with fieldname as key
  41. # @param cls
  42. # @return a list of inserted lodel_id
  43. # @see leobject.datasources.dummy.DummyDatasource.insert(), leobject.letype.LeType.insert()
  44. @classmethod
  45. def insert(cls, letype, datas):
  46. if isinstance(datas, dict):
  47. datas = [datas]
  48. if cls == _LeObject:
  49. raise NotImplementedError("Abstract method")
  50. letype,leclass = cls._prepare_targets(letype)
  51. if letype is None:
  52. raise ValueError("letype argument cannot be None")
  53. for data in datas:
  54. letype.check_datas_or_raise(data, complete = True)
  55. return cls._datasource.insert(letype, leclass, datas)
  56. ## @brief Delete LeObjects given filters
  57. # @param cls
  58. # @param letype LeType|str : LeType child class or name
  59. # @param leclass LeClass|str : LeClass child class or name
  60. # @param filters list : list of filters (see @ref leobject_filters)
  61. # @return bool
  62. @classmethod
  63. def delete(cls, letype, filters):
  64. letype, leclass = cls._prepare_targets(letype)
  65. filters,relationnal_filters = leobject.leobject._LeObject._prepare_filters(filters, letype, leclass)
  66. return cls._datasource.delete(letype, leclass, filters, relationnal_filters)
  67. ## @brief Update LeObjects given filters and datas
  68. # @param cls
  69. # @param letype LeType|str : LeType child class or name
  70. # @param filters list : list of filters (see @ref leobject_filters)
  71. @classmethod
  72. def update(cls, letype, filters, datas):
  73. letype, leclass = cls._prepare_targets(letype)
  74. filters,relationnal_filters = leobject.leobject._LeObject._prepare_filters(filters, letype, leclass)
  75. if letype is None:
  76. raise ValueError("Argument letype cannot be None")
  77. letype.check_datas_or_raise(datas, False)
  78. return cls._datasource.update(letype, leclass, filters, relationnal_filters, datas)
  79. ## @brief make a search to retrieve a collection of LeObject
  80. # @param query_filters list : list of string of query filters (or tuple (FIELD, OPERATOR, VALUE) ) see @ref leobject_filters
  81. # @param field_list list|None : list of string representing fields see @ref leobject_filters
  82. # @param typename str : The name of the LeType we want
  83. # @param classname str : The name of the LeClass we want
  84. # @param cls
  85. # @return responses ({string:*}): a list of dict with field:value
  86. @classmethod
  87. def get(cls, query_filters, field_list = None, typename = None, classname = None):
  88. letype,leclass = cls._prepare_targets(typename, classname)
  89. #Checking field_list
  90. if field_list is None or len(field_list) == 0:
  91. #default field_list
  92. if not (letype is None):
  93. field_list = letype._fields
  94. elif not (leclass is None):
  95. field_list = leclass._fieldtypes.keys()
  96. else:
  97. field_list = list(EditorialModel.classtypes.common_fields.keys())
  98. #Fetching LeType
  99. if letype is None:
  100. if 'type_id' not in field_list:
  101. field_list.append('type_id')
  102. field_list = cls._prepare_field_list(field_list, letype, leclass)
  103. #preparing filters
  104. filters, relationnal_filters = cls._prepare_filters(query_filters, letype, leclass)
  105. #Fetching datas from datasource
  106. datas = cls._datasource.get(leclass, letype, field_list, filters, relationnal_filters)
  107. #Instanciating corresponding LeType child classes with datas
  108. result = list()
  109. for leobj_datas in datas:
  110. letype = self.uid2leobj(datas['type_id']) if letype is None else letype
  111. result.append(letype(datas))
  112. return result
  113. @classmethod
  114. def _prepare_field_list(cls, field_list, letype, leclass):
  115. cls._check_fields(letype, leclass, [f for f in field_list if not cls._field_is_relational(f)])
  116. for i, field in enumerate(field_list):
  117. if cls._field_is_relational(field):
  118. field_list[i] = cls._prepare_relational_field(field)
  119. return field_list
  120. ## @brief Preparing letype and leclass arguments
  121. #
  122. # This function will do multiple things :
  123. # - Convert string to LeType or LeClass child instances
  124. # - If both letype and leclass given, check that letype inherit from leclass
  125. #  - If only a letype is given, fetch the parent leclass
  126. # @note If we give only a leclass as argument returned letype will be None
  127. # @note Its possible to give letype=None and leclass=None. In this case the method will return tuple(None,None)
  128. # @param letype LeType|str|None : LeType child instant or its name
  129. # @param leclass LeClass|str|None : LeClass child instant or its name
  130. # @return a tuple with 2 python classes (LeTypeChild, LeClassChild)
  131. @staticmethod
  132. def _prepare_targets(letype = None , leclass = None):
  133. if not(leclass is None):
  134. if isinstance(leclass, str):
  135. leclass = leobject.lefactory.LeFactory.leobj_from_name(leclass)
  136. if not isinstance(leclass, type) or not (leobject.leclass.LeClass in leclass.__bases__) or leclass.__class__ == leobject.leclass.LeClass:
  137. raise ValueError("None | str | LeType child class excpected, but got : '%s' %s"%(leclass,type(leclass)))
  138. if not(letype is None):
  139. if isinstance(letype, str):
  140. letype = leobject.lefactory.LeFactory.leobj_from_name(letype)
  141. if not isinstance(letype, type) or not leobject.letype.LeType in letype.__bases__ or letype.__class__ == leobject.letype.LeType:
  142. raise ValueError("None | str | LeType child class excpected, but got : %s"%type(letype))
  143. if leclass is None:
  144. leclass = letype._leclass
  145. elif leclass != letype._leclass:
  146. raise ValueError("LeType child class %s does'nt inherite from LeClass %s"%(letype.__name__, leclass.__name__))
  147. return (letype, leclass)
  148. ## @brief Check if a fieldname is valid
  149. # @param letype LeType|None : The concerned type (or None)
  150. # @param leclass LeClass|None : The concerned class (or None)
  151. # @param fields list : List of string representing fields
  152. # @throw LeObjectQueryError if their is some problems
  153. # @throw AttributeError if letype is not from the leclass class
  154. # @todo Delete the checks of letype and leclass and ensure that this method is called with letype and leclass arguments from _prepare_targets()
  155. #
  156. # @see @ref leobject_filters
  157. @staticmethod
  158. def _check_fields(letype, leclass, fields):
  159. #Checking that fields in the query_filters are correct
  160. if letype is None and leclass is None:
  161. #Only fields from the object table are allowed
  162. for field in fields:
  163. if field not in EditorialModel.classtypes.common_fields.keys():
  164. raise LeObjectQueryError("Not typename and no classname given, but the field %s is not in the common_fields list"%field)
  165. else:
  166. if letype is None:
  167. field_l = leclass._fieldtypes.keys()
  168. else:
  169. if not (leclass is None):
  170. if letype._leclass != leclass:
  171. raise AttributeError("The EmType %s is not a specialisation of the EmClass %s"%(typename, classname))
  172. field_l = letype._fields
  173. #Checks that fields are in this type
  174. for field in fields:
  175. if field not in field_l:
  176. raise LeObjectQueryError("No field named '%s' in '%s'"%(field, letype.__name__))
  177. pass
  178. ## @brief Prepare filters for datasource
  179. #
  180. # This method divide filters in two categories :
  181. # - filters : standart FIELDNAME OP VALUE filter
  182. # - relationnal_filters : filter on object relation RELATION_NATURE OP VALUE
  183. #
  184. # Both categories of filters are represented in the same way, a tuple with 3 elements (NAME|NAT , OP, VALUE )
  185. #
  186. # @warning This method assume that letype and leclass are returned from _LeObject._prepare_targets() method
  187. # @param filters_l list : This list can contain str "FIELDNAME OP VALUE" and tuples (FIELDNAME, OP, VALUE)
  188. # @param letype LeType|None : needed to check filters
  189. # @param leclass LeClass|None : needed to check filters
  190. # @return a tuple(FILTERS, RELATIONNAL_FILTERS
  191. #
  192. # @see @ref datasource_side
  193. @staticmethod
  194. def _prepare_filters(filters_l, letype = None, leclass = None):
  195. filters = list()
  196. for fil in filters_l:
  197. if len(fil) == 3 and not isinstance(fil, str):
  198. filters.append(tuple(fil))
  199. else:
  200. filters.append(_LeObject._split_filter(fil))
  201. #Checking relational filters (for the moment fields like superior.NATURE)
  202. relational_filters = [ (_LeObject._prepare_relational_field(field), operator, value) for field, operator, value in filters if _LeObject._field_is_relational(field)]
  203. filters = [f for f in filters if not _LeObject._field_is_relational(f[0])]
  204. #Checking the rest of the fields
  205. _LeObject._check_fields(letype, leclass, [ f[0] for f in filters ])
  206. return (filters, relational_filters)
  207. ## @brief Check if a field is relational or not
  208. # @param field str : the field to test
  209. # @return True if the field is relational else False
  210. @staticmethod
  211. def _field_is_relational(field):
  212. return field.startswith('superior.') or field.startswith('subordinate')
  213. ## @brief Check that a relational field is valid
  214. # @param field str : a relational field
  215. # @return a nature
  216. @staticmethod
  217. def _prepare_relational_field(field):
  218. spl = field.split('.')
  219. if len(spl) != 2:
  220. raise LeObjectQueryError("The relationalfield '%s' is not valid"%field)
  221. nature = spl[-1]
  222. if nature not in EditorialModel.classtypes.EmNature.getall():
  223. raise LeObjectQueryError("'%s' is not a valid nature in the field %s"%(nature, field))
  224. if spl[0] == 'superior':
  225. return (REL_SUP, nature)
  226. elif spl[0] == 'subordinate':
  227. return (REL_SUB, nature)
  228. else:
  229. raise LeObjectQueryError("Invalid preffix for relationnal field : '%s'"%spl[0])
  230. ## @brief Check and split a query filter
  231. # @note The query_filter format is "FIELD OPERATOR VALUE"
  232. # @param query_filter str : A query_filter string
  233. # @param cls
  234. # @return a tuple (FIELD, OPERATOR, VALUE)
  235. @classmethod
  236. def _split_filter(cls, query_filter):
  237. if cls._query_re is None:
  238. cls._compile_query_re()
  239. matches = cls._query_re.match(query_filter)
  240. if not matches:
  241. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  242. result = (matches.group('field'), re.sub(r'\s', ' ', matches.group('operator'), count=0), matches.group('value').strip())
  243. for r in result:
  244. if len(r) == 0:
  245. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  246. return result
  247. ## @brief Compile the regex for query_filter processing
  248. # @note Set _LeObject._query_re
  249. @classmethod
  250. def _compile_query_re(cls):
  251. op_re_piece = '(?P<operator>(%s)'%cls._query_operators[0].replace(' ', '\s')
  252. for operator in cls._query_operators[1:]:
  253. op_re_piece += '|(%s)'%operator.replace(' ', '\s')
  254. op_re_piece += ')'
  255. cls._query_re = re.compile('^\s*(?P<field>(((superior)|(subordinate))\.)?[a-z_][a-z0-9\-_]*)\s*'+op_re_piece+'\s*(?P<value>[^<>=!].*)\s*$', flags=re.IGNORECASE)
  256. pass
  257. class LeObjectError(Exception):
  258. pass
  259. class LeObjectQueryError(LeObjectError):
  260. pass
  261. ## @page leobject_filters LeObject query filters
  262. # The LeObject API provide methods that accept filters allowing the user
  263. # to query the database and fetch LodelEditorialObjects.
  264. #
  265. # The LeObject API translate those filters for the datasource.
  266. #
  267. # @section api_user_side API user side filters
  268. # Filters are string expressing a condition. The string composition
  269. # is as follow : "<FIELD> <OPERATOR> <VALUE>"
  270. # @subsection fpart FIELD
  271. # @subsubsection standart fields
  272. # Standart fields, represents a value of the LeObject for example "title", "lodel_id" etc.
  273. # @subsubsection rfields relationnal fields
  274. # relationnal fields, represents a relation with the object hierarchy. Those fields are composed as follow :
  275. # "<RELATION>.<NATURE>".
  276. #
  277. # - Relation can takes two values : superiors or subordinates
  278. # - Nature is a relation nature ( see EditorialModel.classtypes )
  279. # Examples : "superiors.parent", "subordinates.translation" etc.
  280. # @note The field_list arguement of leobject.leobject._LeObject.get() use the same syntax than the FIELD filter part
  281. # @subsection oppart OPERATOR
  282. # The OPERATOR part of a filter is a comparison operator. There is
  283. # - standart comparison operators : = , <, > , <=, >=, !=
  284. # - list operators : 'in' and 'not in'
  285. # The list of allowed operators is sotred at leobject.leobject._LeObject._query_operators .
  286. # @subsection valpart VALUE
  287. # The VALUE part of a filter is... just a value...
  288. #
  289. # @section datasource_side Datasource side filters
  290. # As said above the API "translate" filters before forwarding them to the datasource.
  291. #
  292. # The translation process transform filters in tuple composed of 3 elements
  293. # ( @ref fpart , @ref oppart , @ref valpart ). Each element is a string.
  294. #
  295. # There is a special case for @ref rfields : the field element is a tuple composed with two elements
  296. # ( RELATION, NATURE ) where NATURE is a string ( see EditorialModel.classtypes ) and RELATION is one of
  297. # the defined constant :
  298. #
  299. # - leobject.leobject.REL_SUB for "subordinates"
  300. # - leobject.leobject.REL_SUP for "superiors"
  301. #
  302. # @note The filters translation process also check if given field are valids compared to the concerned letype and/or the leclass