Без опису
Ви не можете вибрати більше 25 тем Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. #-*- coding: utf-8 -*-
  2. ## @file editorialmodel.py
  3. # Manage instance of an editorial model
  4. from EditorialModel.migrationhandler.dummy import DummyMigrationHandler
  5. from EditorialModel.backend.dummy_backend import EmBackendDummy
  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, EmType, EmFieldGroup, EmField]
  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. return False
  48. return em_class.__name__
  49. ## Loads the structure of the Editorial Model
  50. #
  51. # Gets all the objects contained in that structure and creates a dict indexed by their uids
  52. # @todo Change the thrown exception when a components check fails
  53. # @throw ValueError When a component class don't exists
  54. def load(self):
  55. datas = self.backend.load()
  56. for uid, kwargs in datas.items():
  57. #Store and delete the EmComponent class name from datas
  58. cls_name = kwargs['component']
  59. del kwargs['component']
  60. cls = self.emclass_from_name(cls_name)
  61. if cls:
  62. kwargs['uid'] = uid
  63. # create a dict for the component and one indexed by uids, store instanciated component in it
  64. self._components['uids'][uid] = cls(self, **kwargs)
  65. self._components[cls_name].append(self._components['uids'][uid])
  66. else:
  67. raise ValueError("Unknow EmComponent class : '" + cls_name + "'")
  68. #Sorting by rank
  69. for component_class in Model.components_class:
  70. self.sort_components(component_class)
  71. #Check integrity
  72. for uid, component in self._components['uids'].items():
  73. try:
  74. component.check()
  75. except EmComponentCheckError as exception_object:
  76. raise EmComponentCheckError("The component with uid %d is not valid. Check returns the following error : \"%s\"" % (uid, str(exception_object)))
  77. #Everything is done. Indicating that the component initialisation is over
  78. component.init_ended()
  79. ## Saves data using the current backend
  80. def save(self):
  81. return self.backend.save(self)
  82. ## Given a EmComponent child class return a list of instances
  83. # @param cls EmComponent : A python class
  84. # @return a list of instances or False if the class is not an EmComponent child
  85. def components(self, cls):
  86. key_name = self.name_from_emclass(cls)
  87. return False if key_name is False else self._components[key_name]
  88. ## Return an EmComponent given an uid
  89. # @param uid int : An EmComponent uid
  90. # @return The corresponding instance or False if uid don't exists
  91. def component(self, uid):
  92. return False if uid not in self._components['uids'] else self._components['uids'][uid]
  93. ## Sort components by rank in Model::_components
  94. # @param emclass pythonClass : The type of components to sort
  95. # @throw AttributeError if emclass is not valid
  96. def sort_components(self, component_class):
  97. if component_class not in self.components_class:
  98. raise AttributeError("Bad argument emclass : '" + component_class + "', excpeting one of " + str(self.components_class))
  99. self._components[self.name_from_emclass(component_class)] = sorted(self.components(component_class), key=lambda comp: comp.rank)
  100. ## Return a new uid
  101. # @return a new uid
  102. def new_uid(self):
  103. used_uid = [int(uid) for uid in self._components['uids'].keys()]
  104. return sorted(used_uid)[-1] + 1 if len(used_uid) > 0 else 1
  105. ## Create a component from a component type and datas
  106. #
  107. # @note if datas does not contains a rank the new component will be added last
  108. # @note datas['rank'] can be an integer or two specials strings 'last' or 'first'
  109. # @param component_type str : a component type ( component_class, component_fieldgroup, component_field or component_type )
  110. # @param datas dict : the options needed by the component creation
  111. # @throw ValueError if datas['rank'] is not valid (too big or too small, not an integer nor 'last' or 'first' )
  112. # @todo Handle a raise from the migration handler
  113. def create_component(self, component_type, datas, uid=None):
  114. em_obj = self.emclass_from_name(component_type)
  115. rank = 'last'
  116. if 'rank' in datas:
  117. rank = datas['rank']
  118. del datas['rank']
  119. datas['uid'] = uid if uid else self.new_uid()
  120. em_component = em_obj(self, **datas)
  121. em_component.rank = em_component.get_max_rank() + 1 # Inserting last by default
  122. self._components['uids'][em_component.uid] = em_component
  123. self._components[component_type].append(em_component)
  124. if rank != 'last':
  125. em_component.set_rank(1 if rank == 'first' else rank)
  126. #everything done, indicating that initialisation is over
  127. em_component.init_ended()
  128. #register the creation in migration handler
  129. try:
  130. self.migration_handler.register_change(self, em_component.uid, None, em_component.attr_dump)
  131. except MigrationHandlerChangeError as exception_object:
  132. #Revert the creation
  133. self.components(em_component.__class__).remove(em_component)
  134. del self._components['uids'][em_component.uid]
  135. raise exception_object
  136. self.migration_handler.register_model_state(self, hash(self))
  137. return em_component
  138. ## Delete a component
  139. # @param uid int : Component identifier
  140. # @throw EmComponentNotExistError
  141. # @todo unable uid check
  142. # @todo Handle a raise from the migration handler
  143. def delete_component(self, uid):
  144. #register the deletion in migration handler
  145. self.migration_handler.register_change(self, uid, self.component(uid).attr_dump, None)
  146. em_component = self.component(uid)
  147. if not em_component:
  148. raise EmComponentNotExistError()
  149. if em_component.delete_check():
  150. self._components[self.name_from_emclass(em_component.__class__)].remove(em_component)
  151. del self._components['uids'][uid]
  152. #Register the new EM state
  153. self.migration_handler.register_model_state(self, hash(self))
  154. return True
  155. ## Changes the current backend
  156. #
  157. # @param backend unknown: A backend object
  158. def set_backend(self, backend):
  159. self.backend = backend
  160. ## Returns a list of all the EmClass objects of the model
  161. def classes(self):
  162. return list(self._components[self.name_from_emclass(EmClass)])
  163. ## Use a new migration handler, re-apply all the ME to this handler
  164. #
  165. # @param new_mh MigrationHandler: A migration_handler object
  166. # @warning : if a relational-attribute field (with 'rel_field_id') comes before it's relational field (with 'rel_to_type_id'), this will blow up
  167. def migrate_handler(self, new_mh):
  168. new_me = Model(EmBackendDummy(), new_mh)
  169. relations = {'fields_list': [], 'superiors_list': []}
  170. # re-create component one by one, in components_class[] order
  171. for cls in self.components_class:
  172. for component in self.components(cls):
  173. component_type = self.name_from_emclass(cls)
  174. component_dump = component.attr_dump
  175. del component_dump['model'], component_dump['_inited']
  176. # Save relations between component to apply them later
  177. for relation in relations.keys():
  178. if relation in component_dump and component_dump[relation]:
  179. relations[relation].append((component.uid, component_dump[relation]))
  180. del component_dump[relation]
  181. new_me.create_component(component_type, component_dump, component.uid)
  182. # apply selected field to types
  183. for fields_list in relations['fields_list']:
  184. uid, fields = fields_list
  185. for field_id in fields:
  186. new_me.component(uid).select_field(new_me.component(field_id))
  187. # add superiors to types
  188. # TODO: debug, this add a superior to all types !
  189. for superiors_list in relations['superiors_list']:
  190. uid, sup_list = superiors_list
  191. for nature, superior_uid in sup_list.items():
  192. new_me.component(uid).add_superior(new_me.component(superior_uid), nature)
  193. self.migration_handler = new_mh