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.

model.py 7.9KB

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