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 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. from collections import OrderedDict
  7. import hashlib
  8. import EditorialModel.fieldtypes as ftypes
  9. from EditorialModel.exceptions import *
  10. from Lodel.utils.mlstring import MlString
  11. logger = logging.getLogger('Lodel2.EditorialModel')
  12. ## This class is the mother class of all editorial model objects
  13. #
  14. # It gather all the properties and mechanism that are common to every editorial model objects
  15. # @see EditorialModel::classes::EmClass, EditorialModel::types::EmType, EditorialModel::fieldgroups::EmFieldGroup, EditorialModel::fields::EmField
  16. # @pure
  17. class EmComponent(object):
  18. ## Used by EmComponent::modify_rank
  19. ranked_in = None
  20. def __init__(self, model, uid, name, string = None, help_text = None, date_update = None, date_create = None, rank = None):
  21. if type(self) == EmComponent:
  22. raise NotImplementedError('Abstract class')
  23. self.model = model # AHAH cannot check type without importing Model ?
  24. self.uid = uid
  25. self.check_type('uid', int)
  26. self.name = name
  27. self.check_type('name', str)
  28. self.string = MlString() if string is None else string
  29. self.check_type('string', MlString)
  30. self.help_text = MlString() if help_text is None else help_text
  31. self.check_type('help_text', MlString)
  32. self.date_update = datetime.datetime.now() if date_update is None else date_update #WARNING timezone !
  33. self.check_type('date_update', datetime.datetime)
  34. self.date_create = datetime.datetime.now() if date_create is None else date_create #WARNING timezone !
  35. self.check_type('date_create', datetime.datetime)
  36. #Handling specials ranks for component creation
  37. self.rank = rank
  38. pass
  39. @property
  40. ## @brief Return a dict with attributes name as key and attributes value as value
  41. # @note Used at creation and deletion to call the migration handler
  42. def attr_dump(self):
  43. return { fname : fval for fname, fval in self.__dict__.items() if not fname.startswith('__') }
  44. ## @brief This function has to be called after the instanciation, checks, and init manipulations are done
  45. # @note Create a new attribute _inited that allow __setattr__ to know if it has or not to call the migration handler
  46. def init_ended(self):
  47. self._inited = True
  48. ## @brief Reimplementation for calling the migration handler to register the change
  49. def __setattr__(self, attr_name, value):
  50. inited = '_inited' in self.__dict__
  51. if inited:
  52. # if fails raise MigrationHandlerChangeError
  53. self.model.migration_handler.register_change(self.uid, {attr_name: getattr(self, attr_name) }, {attr_name: value} )
  54. super(EmComponent, self).__setattr__(attr_name, value)
  55. if inited:
  56. self.model.migration_handler.register_model_state(hash(self.model))
  57. ## Check the type of attribute named var_name
  58. # @param var_name str : the attribute name
  59. # @param excepted_type tuple|type : Tuple of type or a type
  60. # @throw AttributeError if wrong type detected
  61. def check_type(self, var_name, excepted_type):
  62. var = getattr(self, var_name)
  63. if not isinstance(var, excepted_type):
  64. raise AttributeError("Excepted %s to be an %s but got %s instead" % (var_name, str(excepted_type), str(type(var))) )
  65. pass
  66. ## @brief Hash function that allows to compare two EmComponent
  67. # @return EmComponent+ClassName+uid
  68. def __hash__(self):
  69. return int(hashlib.md5(str(self.attr_dump).encode('utf-8')).hexdigest(),16)
  70. ## @brief Test if two EmComponent are "equals"
  71. # @return True or False
  72. def __eq__(self, other):
  73. return self.__class__ == other.__class__ and self.uid == other.uid
  74. ## Check if the EmComponent is valid
  75. # This function has to check that rank are correct and continuous other checks are made in childs classes
  76. # @warning Hardcoded minimum rank
  77. # @warning Rank modified by _fields['rank'].value
  78. # @return True
  79. # @throw EmComponentCheckError if fails
  80. def check(self):
  81. if self.get_max_rank() > len(self.same_rank_group()):
  82. #Non continuous ranks
  83. for i, component in enumerate(self.same_rank_group()):
  84. component.rank = i + 1
  85. # No need to sort again here
  86. ## @brief Delete predicate. Indicates if a component can be deleted
  87. # @return True if deletion OK else return False
  88. def delete_check(self):
  89. raise NotImplementedError("Virtual method")
  90. ## @brief Get the maximum rank given an EmComponent child class and a ranked_in filter
  91. # @return A positive integer or -1 if no components
  92. def get_max_rank(self):
  93. components = self.same_rank_group()
  94. return 1 if len(components) == 0 else components[-1].rank
  95. ## Return an array of instances that are concerned by the same rank
  96. # @return An array of instances that are concerned by the same rank
  97. def same_rank_group(self):
  98. components = self.model.components(self.__class__)
  99. ranked_in = self.__class__.ranked_in
  100. return [ c for c in components if getattr(c, ranked_in) == getattr(self, ranked_in) ]
  101. ## Set a new rank for this component
  102. # @note This function assume that ranks are properly set from 1 to x with no gap
  103. #
  104. # @warning Hardcoded minimum rank
  105. # @warning Rank modified by _fields['rank'].value
  106. #
  107. # @param new_rank int: The new rank
  108. #
  109. # @throw TypeError If bad argument type
  110. # @throw ValueError if out of bound value
  111. def set_rank(self, new_rank):
  112. if not isinstance(new_rank, int):
  113. raise TypeError("Excepted <class int> but got "+str(type(new_rank)))
  114. if new_rank <= 0 or new_rank > self.get_max_rank():
  115. raise ValueError("Invalid new rank : "+str(new_rank))
  116. mod = new_rank - self.rank #Indicates the "direction" of the "move"
  117. if mod == 0:
  118. return True
  119. limits = [ self.rank + ( 1 if mod > 0 else -1), new_rank ] #The range of modified ranks
  120. limits.sort()
  121. for component in [ c for c in self.same_rank_group() if c.rank >= limits[0] and c.rank <= limits[1] ] :
  122. component.rank = component.rank + ( -1 if mod > 0 else 1 )
  123. self.rank = new_rank
  124. self.model.sort_components(self.__class__)
  125. pass
  126. ## Modify a rank given an integer modifier
  127. # @param rank_mod int : can be a negative positive or zero integer
  128. # @throw TypeError if rank_mod is not an integer
  129. # @throw ValueError if rank_mod is out of bound
  130. def modify_rank(self, rank_mod):
  131. if not isinstance(rank_mod, int):
  132. raise TypeError("Excepted <class int>, <class str>. But got "+str(type(rank_mod))+", "+str(type(sign)))
  133. try:
  134. self.set_rank(self.rank + rank_mod)
  135. except ValueError:
  136. raise ValueError("The rank modifier '"+str(rank_mod)+"' is out of bounds")
  137. ## @brief Return a string representation of the component
  138. # @return A string representation of the component
  139. def __repr__(self):
  140. if self.name is None:
  141. return "<%s #%s, 'non populated'>" % (type(self).__name__, self.uid)
  142. else:
  143. return "<%s #%s, '%s'>" % (type(self).__name__, self.uid, self.name)
  144. @classmethod
  145. ## Register a new component in UID table
  146. #
  147. # Use the class property table
  148. # @return A new uid (an integer)
  149. def new_uid(cls, db_engine):
  150. if cls.table is None:
  151. raise NotImplementedError("Abstract method")
  152. dbe = db_engine
  153. uidtable = sql.Table('uids', sqlutils.meta(dbe))
  154. conn = dbe.connect()
  155. req = uidtable.insert(values={'table': cls.table})
  156. res = conn.execute(req)
  157. uid = res.inserted_primary_key[0]
  158. logger.debug("Registering a new UID '" + str(uid) + "' for '" + cls.table + "' component")
  159. conn.close()
  160. return uid