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

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