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.

model.py 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #-*- coding: utf-8 -*-
  2. ## @file editorialmodel.py
  3. # Manage instance of an editorial model
  4. import EditorialModel
  5. from EditorialModel.migrationhandler.dummy import DummyMigrationHandler
  6. from EditorialModel.classes import EmClass
  7. from EditorialModel.fieldgroups import EmFieldGroup
  8. from EditorialModel.fields import EmField
  9. from EditorialModel.types import EmType
  10. from EditorialModel.exceptions import EmComponentCheckError, EmComponentNotExistError, MigrationHandlerChangeError
  11. import hashlib
  12. ## Manages the Editorial Model
  13. class Model(object):
  14. components_class = [EmClass, EmField, EmFieldGroup, EmType]
  15. ## Constructor
  16. #
  17. # @param backend unknown: A backend object instanciated from one of the classes in the backend module
  18. def __init__(self, backend, migration_handler=None):
  19. self.migration_handler = DummyMigrationHandler() if migration_handler is None else migration_handler
  20. self.backend = backend
  21. self._components = {'uids': {}, 'EmClass': [], 'EmType': [], 'EmField': [], 'EmFieldGroup': []}
  22. self.load()
  23. def __hash__(self):
  24. components_dump = ""
  25. for _, comp in self._components['uids'].items():
  26. components_dump += str(hash(comp))
  27. hashstring = hashlib.new('sha512')
  28. hashstring.update(components_dump.encode('utf-8'))
  29. return int(hashstring.hexdigest(), 16)
  30. def __eq__(self, other):
  31. return self.__hash__() == other.__hash__()
  32. @staticmethod
  33. ## Given a name return an EmComponent child class
  34. # @param class_name str : The name to identify an EmComponent class
  35. # @return A python class or False if the class_name is not a name of an EmComponent child class
  36. def emclass_from_name(class_name):
  37. for cls in Model.components_class:
  38. if cls.__name__ == class_name:
  39. return cls
  40. return False
  41. @staticmethod
  42. ## Given a python class return a name
  43. # @param cls : The python class we want the name
  44. # @return A class name as string or False if cls is not an EmComponent child class
  45. def name_from_emclass(em_class):
  46. if em_class not in Model.components_class:
  47. spl = em_class.__module__.split('.')
  48. if spl[1] == 'fieldtypes':
  49. return 'EmField'
  50. return False
  51. return em_class.__name__
  52. ## Loads the structure of the Editorial Model
  53. #
  54. # Gets all the objects contained in that structure and creates a dict indexed by their uids
  55. # @todo Change the thrown exception when a components check fails
  56. # @throw ValueError When a component class don't exists
  57. def load(self):
  58. datas = self.backend.load()
  59. for uid, kwargs in datas.items():
  60. #Store and delete the EmComponent class name from datas
  61. cls_name = kwargs['component']
  62. del kwargs['component']
  63. if cls_name == 'EmField':
  64. if not 'type' in kwargs:
  65. raise AttributeError("Missing 'type' from EmField instanciation")
  66. cls = EditorialModel.fields.EmField.get_field_class(kwargs['type'])
  67. del(kwargs['type'])
  68. else:
  69. cls = self.emclass_from_name(cls_name)
  70. if cls:
  71. kwargs['uid'] = uid
  72. # create a dict for the component and one indexed by uids, store instanciated component in it
  73. self._components['uids'][uid] = cls(model=self, **kwargs)
  74. self._components[cls_name].append(self._components['uids'][uid])
  75. else:
  76. raise ValueError("Unknow EmComponent class : '" + cls_name + "'")
  77. #Sorting by rank
  78. for component_class in Model.components_class:
  79. self.sort_components(component_class)
  80. #Check integrity
  81. for uid, component in self._components['uids'].items():
  82. try:
  83. component.check()
  84. except EmComponentCheckError as exception_object:
  85. raise EmComponentCheckError("The component with uid %d is not valid. Check returns the following error : \"%s\"" % (uid, str(exception_object)))
  86. #Everything is done. Indicating that the component initialisation is over
  87. component.init_ended()
  88. ## Saves data using the current backend
  89. def save(self):
  90. return self.backend.save(self)
  91. ## Given a EmComponent child class return a list of instances
  92. # @param cls EmComponent : A python class
  93. # @return a list of instances or False if the class is not an EmComponent child
  94. def components(self, cls):
  95. key_name = self.name_from_emclass(cls)
  96. return False if key_name is False else self._components[key_name]
  97. ## Return an EmComponent given an uid
  98. # @param uid int : An EmComponent uid
  99. # @return The corresponding instance or False if uid don't exists
  100. def component(self, uid):
  101. return False if uid not in self._components['uids'] else self._components['uids'][uid]
  102. ## Sort components by rank in Model::_components
  103. # @param emclass pythonClass : The type of components to sort
  104. # @throw AttributeError if emclass is not valid
  105. # @warning disabled the test on component_class because of EmField new way of working
  106. def sort_components(self, component_class):
  107. #if component_class not in self.components_class:
  108. # raise AttributeError("Bad argument emclass : '" + str(component_class) + "', excpeting one of " + str(self.components_class))
  109. self._components[self.name_from_emclass(component_class)] = sorted(self.components(component_class), key=lambda comp: comp.rank)
  110. ## Return a new uid
  111. # @return a new uid
  112. def new_uid(self):
  113. used_uid = [int(uid) for uid in self._components['uids'].keys()]
  114. return sorted(used_uid)[-1] + 1 if len(used_uid) > 0 else 1
  115. ## Create a component from a component type and datas
  116. #
  117. # @note if datas does not contains a rank the new component will be added last
  118. # @note datas['rank'] can be an integer or two specials strings 'last' or 'first'
  119. # @param component_type str : a component type ( component_class, component_fieldgroup, component_field or component_type )
  120. # @param datas dict : the options needed by the component creation
  121. # @throw ValueError if datas['rank'] is not valid (too big or too small, not an integer nor 'last' or 'first' )
  122. # @todo Handle a raise from the migration handler
  123. # @todo Transform the datas arg in **datas ?
  124. def create_component(self, component_type, datas):
  125. if component_type == 'EmField':
  126. if not 'type' in datas:
  127. raise AttributeError("Missing 'type' from EmField instanciation")
  128. em_obj = EditorialModel.fields.EmField.get_field_class(datas['type'])
  129. del(datas['type'])
  130. else:
  131. em_obj = self.emclass_from_name(component_type)
  132. rank = 'last'
  133. if 'rank' in datas:
  134. rank = datas['rank']
  135. del datas['rank']
  136. datas['uid'] = self.new_uid()
  137. em_component = em_obj(self, **datas)
  138. em_component.rank = em_component.get_max_rank() + 1 #Inserting last by default
  139. self._components['uids'][em_component.uid] = em_component
  140. self._components[self.name_from_emclass(em_component.__class__)].append(em_component)
  141. if rank != 'last':
  142. em_component.set_rank(1 if rank == 'first' else rank)
  143. #everything done, indicating that initialisation is over
  144. em_component.init_ended()
  145. #register the creation in migration handler
  146. try:
  147. self.migration_handler.register_change(self, em_component.uid, None, em_component.attr_dump)
  148. except MigrationHandlerChangeError as exception_object:
  149. #Revert the creation
  150. self.components(em_component.__class__).remove(em_component)
  151. del self._components['uids'][em_component.uid]
  152. raise exception_object
  153. self.migration_handler.register_model_state(self, hash(self))
  154. return em_component
  155. ## Delete a component
  156. # @param uid int : Component identifier
  157. # @throw EmComponentNotExistError
  158. # @todo unable uid check
  159. # @todo Handle a raise from the migration handler
  160. def delete_component(self, uid):
  161. #register the deletion in migration handler
  162. self.migration_handler.register_change(self, uid, self.component(uid).attr_dump, None)
  163. em_component = self.component(uid)
  164. if not em_component:
  165. raise EmComponentNotExistError()
  166. if em_component.delete_check():
  167. self._components[self.name_from_emclass(em_component.__class__)].remove(em_component)
  168. del self._components['uids'][uid]
  169. #Register the new EM state
  170. self.migration_handler.register_model_state(self, hash(self))
  171. return True
  172. ## Changes the current backend
  173. #
  174. # @param backend unknown: A backend object
  175. def set_backend(self, backend):
  176. self.backend = backend
  177. ## Returns a list of all the EmClass objects of the model
  178. def classes(self):
  179. return list(self._components[self.name_from_emclass(EmClass)])