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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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.backend.dummy_backend import EmBackendDummy
  7. from EditorialModel.classes import EmClass
  8. from EditorialModel.fieldgroups import EmFieldGroup
  9. from EditorialModel.fields import EmField
  10. from EditorialModel.types import EmType
  11. from EditorialModel.exceptions import EmComponentCheckError, EmComponentNotExistError, MigrationHandlerChangeError
  12. import hashlib
  13. ## Manages the Editorial Model
  14. class Model(object):
  15. components_class = [EmClass, EmType, EmFieldGroup, EmField]
  16. ## Constructor
  17. #
  18. # @param backend unknown: A backend object instanciated from one of the classes in the backend module
  19. def __init__(self, backend, migration_handler=None):
  20. if migration_handler is None:
  21. self.migration_handler = DummyMigrationHandler()
  22. elif issubclass(migration_handler.__class__, DummyMigrationHandler):
  23. self.migration_handler = migration_handler
  24. else:
  25. raise TypeError("migration_handler should be an instance from a subclass of DummyMigrationhandler")
  26. self.backend = None
  27. self.set_backend(backend)
  28. self._components = {'uids': {}, 'EmClass': [], 'EmType': [], 'EmField': [], 'EmFieldGroup': []}
  29. self.load()
  30. def __hash__(self):
  31. components_dump = ""
  32. for _, comp in self._components['uids'].items():
  33. components_dump += str(hash(comp))
  34. hashstring = hashlib.new('sha512')
  35. hashstring.update(components_dump.encode('utf-8'))
  36. return int(hashstring.hexdigest(), 16)
  37. def __eq__(self, other):
  38. return self.__hash__() == other.__hash__()
  39. @staticmethod
  40. ## Given a name return an EmComponent child class
  41. # @param class_name str : The name to identify an EmComponent class
  42. # @return A python class or False if the class_name is not a name of an EmComponent child class
  43. def emclass_from_name(class_name):
  44. for cls in Model.components_class:
  45. if cls.__name__ == class_name:
  46. return cls
  47. return False
  48. @staticmethod
  49. ## Given a python class return a name
  50. # @param cls : The python class we want the name
  51. # @return A class name as string or False if cls is not an EmComponent child class
  52. # @todo réécrire le split, c'est pas bô
  53. def name_from_emclass(em_class):
  54. if em_class not in Model.components_class:
  55. if issubclass(em_class, EmField):
  56. return 'EmField'
  57. return False
  58. return em_class.__name__
  59. ## Loads the structure of the Editorial Model
  60. #
  61. # Gets all the objects contained in that structure and creates a dict indexed by their uids
  62. # @todo Change the thrown exception when a components check fails
  63. # @throw ValueError When a component class don't exists
  64. def load(self):
  65. datas = self.backend.load()
  66. for uid, kwargs in datas.items():
  67. #Store and delete the EmComponent class name from datas
  68. cls_name = kwargs['component']
  69. del kwargs['component']
  70. if cls_name == 'EmField':
  71. #Special EmField process because of fieldtypes
  72. if not 'fieldtype' in kwargs:
  73. raise AttributeError("Missing 'fieldtype' from EmField instanciation")
  74. cls = EditorialModel.fields.EmField.get_field_class(kwargs['fieldtype'])
  75. else:
  76. cls = self.emclass_from_name(cls_name)
  77. if cls:
  78. kwargs['uid'] = uid
  79. # create a dict for the component and one indexed by uids, store instanciated component in it
  80. self._components['uids'][uid] = cls(model=self, **kwargs)
  81. self._components[cls_name].append(self._components['uids'][uid])
  82. else:
  83. raise ValueError("Unknow EmComponent class : '" + cls_name + "'")
  84. #Sorting by rank
  85. for component_class in Model.components_class:
  86. self.sort_components(component_class)
  87. #Check integrity
  88. for uid, component in self._components['uids'].items():
  89. try:
  90. component.check()
  91. except EmComponentCheckError as exception_object:
  92. raise EmComponentCheckError("The component with uid %d is not valid. Check returns the following error : \"%s\"" % (uid, str(exception_object)))
  93. #Everything is done. Indicating that the component initialisation is over
  94. component.init_ended()
  95. ## Saves data using the current backend
  96. # @param filename str | None : if None use the current backend file (provided at backend instanciation)
  97. def save(self, filename = None):
  98. return self.backend.save(self, filename)
  99. ## Given a EmComponent child class return a list of instances
  100. # @param cls EmComponent : A python class
  101. # @return a list of instances or False if the class is not an EmComponent child
  102. def components(self, cls=None):
  103. if cls is None:
  104. return [ self.component(uid) for uid in self._components['uids'] ]
  105. key_name = self.name_from_emclass(cls)
  106. return False if key_name is False else self._components[key_name]
  107. ## Return an EmComponent given an uid
  108. # @param uid int : An EmComponent uid
  109. # @return The corresponding instance or False if uid don't exists
  110. def component(self, uid):
  111. return False if uid not in self._components['uids'] else self._components['uids'][uid]
  112. ## Sort components by rank in Model::_components
  113. # @param emclass pythonClass : The type of components to sort
  114. # @throw AttributeError if emclass is not valid
  115. # @warning disabled the test on component_class because of EmField new way of working
  116. def sort_components(self, component_class):
  117. #if component_class not in self.components_class:
  118. # raise AttributeError("Bad argument emclass : '" + str(component_class) + "', excpeting one of " + str(self.components_class))
  119. self._components[self.name_from_emclass(component_class)] = sorted(self.components(component_class), key=lambda comp: comp.rank)
  120. ## Return a new uid
  121. # @return a new uid
  122. def new_uid(self):
  123. used_uid = [int(uid) for uid in self._components['uids'].keys()]
  124. return sorted(used_uid)[-1] + 1 if len(used_uid) > 0 else 1
  125. ## Create a component from a component type and datas
  126. #
  127. # @note if datas does not contains a rank the new component will be added last
  128. # @note datas['rank'] can be an integer or two specials strings 'last' or 'first'
  129. # @param component_type str : a component type ( component_class, component_fieldgroup, component_field or component_type )
  130. # @param datas dict : the options needed by the component creation
  131. # @throw ValueError if datas['rank'] is not valid (too big or too small, not an integer nor 'last' or 'first' )
  132. # @todo Handle a raise from the migration handler
  133. # @todo Transform the datas arg in **datas ?
  134. def create_component(self, component_type, datas, uid=None):
  135. if not (uid is None) and (not isinstance(uid, int) or uid <= 0 or uid in self._components['uids']):
  136. raise ValueError("Invalid uid provided")
  137. if component_type not in [ n for n in self._components.keys() if n != 'uids' ]:
  138. raise ValueError("Invalid component_type rpovided")
  139. elif component_type == 'EmField':
  140. #special process for EmField
  141. if not 'fieldtype' in datas:
  142. raise AttributeError("Missing 'fieldtype' from EmField instanciation")
  143. em_obj = EditorialModel.fields.EmField.get_field_class(datas['fieldtype'])
  144. else:
  145. em_obj = self.emclass_from_name(component_type)
  146. rank = 'last'
  147. if 'rank' in datas:
  148. rank = datas['rank']
  149. del datas['rank']
  150. datas['uid'] = uid if uid else self.new_uid()
  151. em_component = em_obj(model=self, **datas)
  152. em_component.rank = em_component.get_max_rank() + 1 # Inserting last by default
  153. self._components['uids'][em_component.uid] = em_component
  154. self._components[component_type].append(em_component)
  155. if rank != 'last':
  156. em_component.set_rank(1 if rank == 'first' else rank)
  157. #everything done, indicating that initialisation is over
  158. em_component.init_ended()
  159. #register the creation in migration handler
  160. try:
  161. self.migration_handler.register_change(self, em_component.uid, None, em_component.attr_dump())
  162. except MigrationHandlerChangeError as exception_object:
  163. #Revert the creation
  164. self.components(em_component.__class__).remove(em_component)
  165. del self._components['uids'][em_component.uid]
  166. raise exception_object
  167. self.migration_handler.register_model_state(self, hash(self))
  168. return em_component
  169. ## Delete a component
  170. # @param uid int : Component identifier
  171. # @throw EmComponentNotExistError
  172. # @todo unable uid check
  173. # @todo Handle a raise from the migration handler
  174. def delete_component(self, uid):
  175. em_component = self.component(uid)
  176. if not em_component:
  177. raise EmComponentNotExistError()
  178. if em_component.delete_check():
  179. #register the deletion in migration handler
  180. self.migration_handler.register_change(self, uid, self.component(uid).attr_dump(), None)
  181. # delete internal lists
  182. self._components[self.name_from_emclass(em_component.__class__)].remove(em_component)
  183. del self._components['uids'][uid]
  184. #Register the new EM state
  185. self.migration_handler.register_model_state(self, hash(self))
  186. return True
  187. return False
  188. ## Changes the current backend
  189. #
  190. # @param backend unknown: A backend object
  191. def set_backend(self, backend):
  192. if issubclass(backend.__class__, EmBackendDummy):
  193. self.backend = backend
  194. else:
  195. raise TypeError('Backend should be an instance of a EmBackednDummy subclass')
  196. ## Returns a list of all the EmClass objects of the model
  197. def classes(self):
  198. return list(self._components[self.name_from_emclass(EmClass)])
  199. ## Use a new migration handler, re-apply all the ME to this handler
  200. #
  201. # @param new_mh MigrationHandler: A migration_handler object
  202. # @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
  203. def migrate_handler(self, new_mh):
  204. new_me = Model(EmBackendDummy(), new_mh)
  205. relations = {'fields_list': [], 'superiors_list': []}
  206. # re-create component one by one, in components_class[] order
  207. for cls in self.components_class:
  208. for component in self.components(cls):
  209. component_type = self.name_from_emclass(cls)
  210. component_dump = component.attr_dump()
  211. # Save relations between component to apply them later
  212. for relation in relations.keys():
  213. if relation in component_dump and component_dump[relation]:
  214. relations[relation].append((component.uid, component_dump[relation]))
  215. del component_dump[relation]
  216. new_me.create_component(component_type, component_dump, component.uid)
  217. # apply selected field to types
  218. for fields_list in relations['fields_list']:
  219. uid, fields = fields_list
  220. for field_id in fields:
  221. new_me.component(uid).select_field(new_me.component(field_id))
  222. # add superiors to types
  223. for superiors_list in relations['superiors_list']:
  224. uid, sup_list = superiors_list
  225. for nature, superiors_uid in sup_list.items():
  226. for superior_uid in superiors_uid:
  227. new_me.component(uid).add_superior(new_me.component(superior_uid), nature)
  228. del new_me
  229. self.migration_handler = new_mh