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.

components.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # -*- coding: utf-8 -*-
  2. ## @file components.py
  3. # Defines the EditorialModel::components::EmComponent class and the EditorialModel::components::ComponentNotExistError exception class
  4. import datetime
  5. import logging
  6. import EditorialModel.fieldtypes as ftypes
  7. from collections import OrderedDict
  8. logger = logging.getLogger('Lodel2.EditorialModel')
  9. ## This class is the mother class of all editorial model objects
  10. #
  11. # It gather all the properties and mechanism that are common to every editorial model objects
  12. # @see EditorialModel::classes::EmClass, EditorialModel::types::EmType, EditorialModel::fieldgroups::EmFieldGroup, EditorialModel::fields::EmField
  13. # @pure
  14. class EmComponent(object):
  15. ## Used by EmComponent::modify_rank
  16. ranked_in = None
  17. ## Read only properties
  18. _ro_properties = ['date_update', 'date_create', 'uid', 'rank', 'deleted']
  19. ## @brief List fields name and fieldtype
  20. #
  21. # This is a list that describe database fields common for each EmComponent child classes.
  22. # A database field is defined here by a tuple(name, type) with name a string and type an EditorialModel.fieldtypes.EmFieldType
  23. # @warning The EmFieldType in second position in the tuples must be a class type and not a class instance !!!
  24. # @see EditorialModel::classes::EmClass::_fields EditorialModel::fieldgroups::EmFieldGroup::_fields EditorialModel::types::EmType::_fields EditorialModel::fields::EmField::_fields
  25. _fields = [
  26. ('uid', ftypes.EmField_integer),
  27. ('name', ftypes.EmField_char),
  28. ('rank', ftypes.EmField_integer),
  29. ('date_update', ftypes.EmField_date),
  30. ('date_create', ftypes.EmField_date),
  31. ('string', ftypes.EmField_mlstring),
  32. ('help', ftypes.EmField_mlstring)
  33. ]
  34. ## Instaciate an EmComponent
  35. # @param id_or_name int|str: name or id of the object
  36. # @throw TypeError if id_or_name is not an integer nor a string
  37. # @throw NotImplementedError if called with EmComponent
  38. def __init__(self, data):
  39. if type(self) == EmComponent:
  40. raise NotImplementedError('Abstract class')
  41. ## @brief An OrderedDict storing fields name and values
  42. # Values are handled by EditorialModel::fieldtypes::EmFieldType
  43. # @warning \ref _fields instance property is not the same than EmComponent::_fields class property. In the instance property the EditorialModel::fieldtypes::EmFieldType are instanciated to be able to handle datas
  44. # @see EmComponent::_fields EditorialModel::fieldtypes::EmFieldType
  45. self._fields = OrderedDict([(name, ftype()) for (name, ftype) in (EmComponent._fields + self.__class__._fields)])
  46. for name, value in data.items():
  47. if name in self._fields:
  48. self._fields[name].from_string(value)
  49. ## @brief Access an attribute of an EmComponent
  50. # This method is overloads the default __getattr__ to search in EmComponents::_fields . If there is an EditorialModel::EmField with a corresponding name in the component
  51. # it returns its value.
  52. # @param name str: The attribute name
  53. # @throw AttributeError if attribute don't exists
  54. # @see EditorialModel::EmField::value
  55. def __getattr__(self, name):
  56. if name != '_fields' and name in self._fields:
  57. return self._fields[name].value
  58. else:
  59. return super(EmComponent, self).__getattribute__(name)
  60. ## @brief Access an EmComponent attribute
  61. # This function overload the default __getattribute__ in order to check if the EmComponent was deleted.
  62. # @param name str: The attribute name
  63. # @throw EmComponentNotExistError if the component was deleted
  64. def __getattribute__(self, name):
  65. if super(EmComponent, self).__getattribute__('deleted'):
  66. raise EmComponentNotExistError("This " + super(EmComponent, self).__getattribute__('__class__').__name__ + " has been deleted")
  67. res = super(EmComponent, self).__getattribute(name)
  68. return res
  69. ## Set the value of an EmComponent attribute
  70. # @param name str: The propertie name
  71. # @param value *: The value
  72. def __setattr__(self, name, value):
  73. if name in self.__class__._ro_properties:
  74. raise TypeError("Propertie '" + name + "' is readonly")
  75. if name != '_fields' and hasattr(self, '_fields') and name in object.__getattribute__(self, '_fields'):
  76. self._fields[name].from_python(value)
  77. else:
  78. object.__setattr__(self, name, value)
  79. ## @brief Hash function that allows to compare two EmComponent
  80. # @return EmComponent+ClassName+uid
  81. def __hash__(self):
  82. return "EmComponent"+self.__class__.__name__+str(self.uid)
  83. ## @brief Test if two EmComponent are "equals"
  84. # @return True or False
  85. def __eq__(self, other):
  86. return self.__class__ == other.__class__ and self.uid == other.uid
  87. ## Set all fields
  88. def populate(self):
  89. records = [] # TODO
  90. for record in records:
  91. for keys in self._fields.keys():
  92. if keys in record:
  93. self._fields[keys].from_string(record[keys])
  94. super(EmComponent, self).__setattr__('deleted', False)
  95. ## Insert a new component
  96. #
  97. # This function create and assign a new UID and handle the date_create and date_update values
  98. # @warning There is a mandatory argument dbconf that indicate wich database configuration to use
  99. # @param **kwargs : Names arguments representing object properties
  100. # @return An instance of the created component
  101. # @throw TypeError if an element of kwargs isn't a valid object propertie or if a mandatory argument is missing
  102. # @throw RuntimeError if the creation fails at database level
  103. # @todo Check that every mandatory _fields are given in args
  104. # @todo Stop using datetime.datetime.utcnow() for date_update and date_create init
  105. @classmethod
  106. def create(cls, **kwargs):
  107. #Checking for invalid arguments
  108. valid_args = [ name for name,_ in (cls._fields + EmComponent._fields)]
  109. for argname in kwargs:
  110. if argname in ['date_update', 'date_create', 'rank', 'uid']: # Automatic properties
  111. raise TypeError("Invalid argument : " + argname)
  112. elif argname not in valid_args:
  113. raise TypeError("Unexcepted keyword argument '" + argname + "' for " + cls.__name__ + " creation")
  114. #Check uniq names constraint
  115. try:
  116. name = kwargs['name']
  117. exist = cls(name)
  118. for kname in kwargs:
  119. if not (getattr(exist, kname) == kwargs[kname]):
  120. raise EmComponentExistError("An " + cls.__name__ + " named " + name + " allready exists with a different " + kname)
  121. logger.info("Trying to create an " + cls.__name__ + " that allready exist with same attribute. Returning the existing one")
  122. return exist
  123. except EmComponentNotExistError:
  124. pass
  125. kwargs['uid'] = cls.new_uid()
  126. kwargs['date_update'] = kwargs['date_create'] = datetime.datetime.utcnow()
  127. kwargs['rank'] = cls._get_max_rank( kwargs[cls.ranked_in], dbe )+1
  128. return cls(kwargs['name'], dbconf)
  129. ## Delete this component
  130. # @return bool : True if deleted False if deletion aborded
  131. # @throw RunTimeError if it was unable to do the deletion
  132. def delete(self):
  133. pass
  134. ## @brief Get the maximum rank given an EmComponent child class and a ranked_in filter
  135. # @param ranked_in_value mixed: The rank "family"
  136. # @return -1 if no EmComponent found else return an integer >= 0
  137. @classmethod
  138. def _get_max_rank(cls, ranked_in_value):
  139. pass
  140. ## Only make a call to the class method
  141. # @return A positive integer or -1 if no components
  142. # @see EmComponent::_get_max_rank()
  143. def get_max_rank(self, ranked_in_value):
  144. return self.__class__._get_max_rank(ranked_in_value)
  145. ## Set a new rank for this component
  146. # @note This function assume that ranks are properly set from 1 to x with no gap
  147. # @param new_rank int: The new rank
  148. # @return True if success False if not
  149. # @throw TypeError If bad argument type
  150. # @throw ValueError if out of bound value
  151. def set_rank(self, new_rank):
  152. if not isinstance(new_rank, int):
  153. raise TypeError("Excepted <class int> but got "+str(type(new_rank)))
  154. if new_rank < 0 or new_rank > self.get_max_rank(getattr(self, self.ranked_in)):
  155. raise ValueError("Invalid new rank : "+str(new_rank))
  156. mod = new_rank - self.rank #Allow to know the "direction" of the "move"
  157. if mod == 0: #No modifications
  158. return True
  159. limits = [ self.rank + ( 1 if mod > 0 else -1), new_rank ] #The range of modified ranks
  160. limits.sort()
  161. dbe = self.db_engine
  162. conn = dbe.connect()
  163. table = sqlutils.get_table(self)
  164. #Selecting the components that will be modified
  165. req = table.select().where( getattr(table.c, self.ranked_in) == getattr(self, self.ranked_in)).where(table.c.rank >= limits[0]).where(table.c.rank <= limits[1])
  166. res = conn.execute(req)
  167. if not res: #Db error... Maybe false is a bit silent for a failuer
  168. return False
  169. rows = res.fetchall()
  170. updated_ranks = [{'b_uid': self.uid, 'b_rank': new_rank}]
  171. for row in rows:
  172. updated_ranks.append({'b_uid': row['uid'], 'b_rank': row['rank'] + (-1 if mod > 0 else 1)})
  173. req = table.update().where(table.c.uid == sql.bindparam('b_uid')).values(rank=sql.bindparam('b_rank'))
  174. res = conn.execute(req, updated_ranks)
  175. conn.close()
  176. if res:
  177. #Instance rank update
  178. self._fields['rank'].value = new_rank
  179. return bool(res)
  180. ## @brief Modify a rank given a sign and a new_rank
  181. # - If sign is '=' set the rank to new_rank
  182. # - If sign is '-' set the rank to cur_rank - new_rank
  183. # - If sign is '+' set the rank to cur_rank + new_rank
  184. # @param new_rank int: The new_rank or rank modifier
  185. # @param sign str: Can be one of '=', '+', '-'
  186. # @return True if success False if fails
  187. # @throw TypeError If bad argument type
  188. # @throw ValueError if out of bound value
  189. def modify_rank(self,new_rank, sign='='):
  190. if not isinstance(new_rank, int) or not isinstance(sign, str):
  191. raise TypeError("Excepted <class int>, <class str>. But got "+str(type(new_rank))+", "+str(type(sign)))
  192. if sign == '+':
  193. return self.set_rank(self.rank + new_rank)
  194. elif sign == '-':
  195. return self.set_rank(self.rank - new_rank)
  196. elif sign == '=':
  197. return self.set_rank(new_rank)
  198. else:
  199. raise ValueError("Excepted one of '=', '+', '-' for sign argument, but got "+sign)
  200. ## @brief Return a string representation of the component
  201. # @return A string representation of the component
  202. def __repr__(self):
  203. if self.name is None:
  204. return "<%s #%s, 'non populated'>" % (type(self).__name__, self.uid)
  205. else:
  206. return "<%s #%s, '%s'>" % (type(self).__name__, self.uid, self.name)
  207. @classmethod
  208. ## Register a new component in UID table
  209. #
  210. # Use the class property table
  211. # @return A new uid (an integer)
  212. def new_uid(cls, db_engine):
  213. if cls.table is None:
  214. raise NotImplementedError("Abstract method")
  215. dbe = db_engine
  216. uidtable = sql.Table('uids', sqlutils.meta(dbe))
  217. conn = dbe.connect()
  218. req = uidtable.insert(values={'table': cls.table})
  219. res = conn.execute(req)
  220. uid = res.inserted_primary_key[0]
  221. logger.debug("Registering a new UID '" + str(uid) + "' for '" + cls.table + "' component")
  222. conn.close()
  223. return uid
  224. ## @brief An exception class to tell that a component don't exist
  225. class EmComponentNotExistError(Exception):
  226. pass
  227. ## @brief Raised on uniq constraint error at creation
  228. # This exception class is dedicated to be raised when create() method is called
  229. # if an EmComponent with this name but different parameters allready exist
  230. class EmComponentExistError(Exception):
  231. pass
  232. ## @brief An exception class to tell that no ranking exist yet for the group of the object
  233. class EmComponentRankingNotExistError(Exception):
  234. pass