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.

django.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import sys
  4. import django
  5. from django.db import models
  6. from django.db.models.loading import cache as django_cache
  7. from django.core.exceptions import ValidationError
  8. from EditorialModel.migrationhandler.dummy import DummyMigrationHandler
  9. from EditorialModel.exceptions import *
  10. ## @brief Create a django model
  11. # @param name str : The django model name
  12. # @param fields dict : A dict that contains fields name and type ( str => DjangoField )
  13. # @param app_label str : The name of the applications that will have those models
  14. # @param module str : The module name this model will belong to
  15. # @param options dict : Dict of options (name => value)
  16. # @param admin_opts dict : Dict of options for admin part of this model
  17. # @param parent_class str : Parent class name
  18. # @return A dynamically created django model
  19. # @note Source : https://code.djangoproject.com/wiki/DynamicModels
  20. #
  21. def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None, parent_class=None):
  22. class Meta:
  23. # Using type('Meta', ...) gives a dictproxy error during model creation
  24. pass
  25. if app_label:
  26. # app_label must be set using the Meta inner class
  27. setattr(Meta, 'app_label', app_label)
  28. # Update Meta with any options that were provided
  29. if options is not None:
  30. for key, value in options.iteritems():
  31. setattr(Meta, key, value)
  32. # Set up a dictionary to simulate declarations within a class
  33. attrs = {'__module__': module, 'Meta': Meta}
  34. # Add in any fields that were provided
  35. if fields:
  36. attrs.update(fields)
  37. # Create the class, which automatically triggers ModelBase processing
  38. if parent_class is None:
  39. parent_class = models.Model
  40. model = type(name, (parent_class,), attrs)
  41. # Create an Admin class if admin options were provided
  42. if admin_opts is not None:
  43. class Admin(admin.ModelAdmin):
  44. pass
  45. for key, value in admin_opts:
  46. setattr(Admin, key, value)
  47. admin.site.register(model, Admin)
  48. return model
  49. ## @package EditorialModel.migrationhandler.django
  50. # @brief A migration handler for django ORM
  51. #
  52. # Create django models according to the editorial model
  53. class DjangoMigrationHandler(DummyMigrationHandler):
  54. ## @brief Instanciate a new DjangoMigrationHandler
  55. # @param app_name str : The django application name for models generation
  56. # @param debug bool : Set to True to be in debug mode
  57. # @param dryrun bool : If true don't do any migration, only simulate them
  58. def __init__(self, app_name, debug=False, dryrun=False):
  59. self.debug = debug
  60. self.app_name = app_name
  61. self.dryrun = dryrun
  62. ## @brief Record a change in the EditorialModel and indicate wether or not it is possible to make it
  63. # @note The states ( initial_state and new_state ) contains only fields that changes
  64. #
  65. # @note Migration is not applied by this method. This method only checks if the new em is valid
  66. #
  67. # @param em model : The EditorialModel.model object to provide the global context
  68. # @param uid int : The uid of the change EmComponent
  69. # @param initial_state dict | None : dict with field name as key and field value as value. Representing the original state. None mean creation of a new component.
  70. # @param new_state dict | None : dict with field name as key and field value as value. Representing the new state. None mean component deletion
  71. # @throw EditorialModel.exceptions.MigrationHandlerChangeError if the change was refused
  72. # @todo Some tests about strating django in this method
  73. # @todo Rename in something like "validate_change"
  74. #
  75. # @warning broken because of : https://code.djangoproject.com/ticket/24735 you have to patch django/core/management/commands/makemigrations.py w/django/core/management/commands/makemigrations.py
  76. def register_change(self, em, uid, initial_state, new_state):
  77. #Starting django
  78. os.environ['LODEL_MIGRATION_HANDLER_TESTS'] = 'YES'
  79. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Lodel.settings")
  80. django.setup()
  81. from django.contrib import admin
  82. from django.core.management import call_command as django_cmd
  83. if self.debug:
  84. self.dump_migration(uid, initial_state, new_state)
  85. #Generation django models
  86. self.em_to_models(em)
  87. try:
  88. #Calling makemigrations to see if the migration is valid
  89. #django_cmd('makemigrations', self.app_name, dry_run=True, interactive=False, merge=True)
  90. django_cmd('makemigrations', self.app_name, dry_run=True, interactive=False)
  91. except django.core.management.base.CommandError as e:
  92. raise MigrationHandlerChangeError(str(e))
  93. return True
  94. ## @brief Print a debug message representing a migration
  95. # @param uid int : The EmComponent uid
  96. # @param initial_state dict | None : dict representing the fields that are changing
  97. # @param new_state dict | None : dict represnting the new fields states
  98. def dump_migration(self, uid, initial_state, new_state):
  99. if self.debug:
  100. print("\n##############")
  101. print("DummyMigrationHandler debug. Changes for component with uid %d :" % uid)
  102. if initial_state is None:
  103. print("Component creation (uid = %d): \n\t" % uid, new_state)
  104. elif new_state is None:
  105. print("Component deletion (uid = %d): \n\t" % uid, initial_state)
  106. else:
  107. field_list = set(initial_state.keys()).union(set(new_state.keys()))
  108. for field_name in field_list:
  109. str_chg = "\t%s " % field_name
  110. if field_name in initial_state:
  111. str_chg += "'" + str(initial_state[field_name]) + "'"
  112. else:
  113. str_chg += " creating "
  114. str_chg += " => "
  115. if field_name in new_state:
  116. str_chg += "'" + str(new_state[field_name]) + "'"
  117. else:
  118. str_chg += " deletion "
  119. print(str_chg)
  120. print("##############\n")
  121. pass
  122. ## @brief Register a new model state and update the data representation given the new state
  123. # @param em model : The EditorialModel to migrate
  124. # @param state_hash str : Note usefull (for the moment ?)
  125. # @todo Rename this method in something like "model_migrate"
  126. def register_model_state(self, em, state_hash):
  127. if self.dryrun:
  128. return
  129. if self.debug:
  130. print("Applying editorial model change")
  131. #Starting django
  132. os.environ['LODEL_MIGRATION_HANDLER_TESTS'] = 'YES'
  133. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Lodel.settings")
  134. django.setup()
  135. from django.contrib import admin
  136. from django.core.management import call_command as django_cmd
  137. #Generation django models
  138. self.em_to_models(em)
  139. try:
  140. #Calling makemigrations
  141. django_cmd('makemigrations', self.app_name, interactive=False)
  142. except django.core.management.base.CommandError as e:
  143. raise MigrationHandlerChangeError(str(e))
  144. try:
  145. #Calling migrate to update the database schema
  146. django_cmd('migrate', self.app_name, interactive=False, noinput=True)
  147. except django.core.management.base.CommandError as e:
  148. raise MigrationHandlerChangeError("Unable to migrate to new model state : %s" % e)
  149. pass
  150. ## @brief Return the models save method
  151. #
  152. # The save function of our class and type models is used to set unconditionnaly the
  153. # classtype, class_name and type_name models property
  154. #
  155. # @param classname str: The classname used to call the super().save
  156. # @param level str: Wich type of model are we doing. Possible values are 'class' and 'type'
  157. # @param datas list : List of property => value to set in the save function
  158. # @return The wanted save function
  159. def get_save_fun(self, classname, level, datas):
  160. if level == 'class':
  161. def save(self, *args, **kwargs):
  162. self.classtype = datas['classtype']
  163. self.class_name = datas['class_name']
  164. super(classname, self).save(*args, **kwargs)
  165. elif level == 'type':
  166. def save(self, *args, **kwargs):
  167. self.type_name = datas['type_name']
  168. super(classname, self).save(*args, **kwargs)
  169. return save
  170. ## @brief Create django models from an EditorialModel.model object
  171. # @param edMod EditorialModel.model.Model : The editorial model instance
  172. # @return a dict with all the models
  173. # @todo Handle fieldgroups
  174. # @todo write and use a function to forge models name from EmClasses and EmTypes names
  175. # @note There is a problem with the related_name for superiors fk : The related name cannot be subordinates, it has to be the subordinates em_type name
  176. def em_to_models(self, edMod):
  177. module_name = self.app_name + '.models'
  178. #Purging django models cache
  179. if self.app_name in django_cache.all_models:
  180. for modname in django_cache.all_models[self.app_name]:
  181. del(django_cache.all_models[self.app_name][modname])
  182. #del(django_cache.all_models[self.app_name])
  183. app_name = self.app_name
  184. #Creating the document model
  185. document_attrs = {
  186. 'lodel_id': models.AutoField(primary_key=True),
  187. 'classtype': models.CharField(max_length=16, editable=False),
  188. 'class_name': models.CharField(max_length=16, editable=False),
  189. 'type_name': models.CharField(max_length=16, editable=False),
  190. 'string': models.CharField(max_length=255),
  191. 'date_update': models.DateTimeField(auto_now=True, auto_now_add=True),
  192. 'date_create': models.DateTimeField(auto_now_add=True),
  193. 'rank': models.IntegerField(),
  194. 'help_text': models.CharField(max_length=255),
  195. }
  196. #Creating the base model document
  197. document_model = create_model('document', document_attrs, self.app_name, module_name)
  198. django_models = {'doc': document_model, 'classes': {}, 'types': {}}
  199. classes = edMod.classes()
  200. #Creating the EmClasses models with document inheritance
  201. for emclass in classes:
  202. emclass_fields = {
  203. 'save': self.get_save_fun(emclass.uniq_name, 'class', {'classtype': emclass.classtype, 'class_name': emclass.uniq_name}),
  204. }
  205. #Addding non optionnal fields
  206. for emfield in emclass.fields():
  207. if not emfield.optional:
  208. # !!! Replace with fieldtype 2 django converter
  209. #emclass_fields[emfield.uniq_name] = models.CharField(max_length=56, default=emfield.uniq_name)
  210. emclass_fields[emfield.uniq_name] = self.field_to_django(emfield, emclass)
  211. #print("Model for class %s created with fields : "%emclass.uniq_name, emclass_fields)
  212. if self.debug:
  213. print("Model for class %s created" % emclass.uniq_name)
  214. django_models['classes'][emclass.uniq_name] = create_model(emclass.uniq_name, emclass_fields, self.app_name, module_name, parent_class=django_models['doc'])
  215. #Creating the EmTypes models with EmClass inherithance
  216. for emtype in emclass.types():
  217. emtype_fields = {
  218. 'save': self.get_save_fun(emtype.uniq_name, 'type', {'type_name': emtype.uniq_name}),
  219. }
  220. #Adding selected optionnal fields
  221. for emfield in emtype.selected_fields():
  222. #emtype_fields[emfield.uniq_name] = models.CharField(max_length=56, default=emfield.uniq_name)
  223. emtype_fields[emfield.uniq_name] = self.field_to_django(emfield, emtype)
  224. #Adding superiors foreign key
  225. for nature, superiors_list in emtype.superiors().items():
  226. for superior in superiors_list:
  227. emtype_fields[nature] = models.ForeignKey(superior.uniq_name, related_name=emtype.uniq_name, null=True)
  228. if self.debug:
  229. print("Model for type %s created" % emtype.uniq_name)
  230. django_models['types'][emtype.uniq_name] = create_model(emtype.uniq_name, emtype_fields, self.app_name, module_name, parent_class=django_models['classes'][emclass.uniq_name])
  231. pass
  232. ## @brief Return a good django field type given a field
  233. # @param f EmField : an EmField object
  234. # @param assoc_comp EmComponent : The associated component (type or class)
  235. # @return A django field instance
  236. # @note The manytomany fields created with the rel2type field has no related_name associated to it
  237. def field_to_django(self, f, assoc_comp):
  238. #Building the args dictionnary for django field instanciation
  239. args = dict()
  240. args['null'] = f.nullable
  241. if not (f.default is None):
  242. args['default'] = f.default
  243. v_fun = f.validation_function(raise_e=ValidationError)
  244. if v_fun:
  245. args['validators'] = [v_fun]
  246. if f.uniq:
  247. args['unique'] = True
  248. # Field instanciation
  249. if f.ftype == 'char': # varchar field
  250. args['max_length'] = f.max_length
  251. return models.CharField(**args)
  252. elif f.ftype == 'int': # integer field
  253. return models.IntegerField(**args)
  254. elif f.ftype == 'text': # text field
  255. return models.TextField(**args)
  256. elif f.ftype == 'datetime': # Datetime field
  257. args['auto_now'] = f.now_on_update
  258. args['auto_now_add'] = f.now_on_create
  259. return models.DateTimeField(**args)
  260. elif f.ftype == 'bool': # Boolean field
  261. if args['null']:
  262. return models.NullBooleanField(**args)
  263. del(args['null'])
  264. return models.BooleanField(**args)
  265. elif f.ftype == 'rel2type': # Relation to type
  266. if assoc_comp is None:
  267. raise RuntimeError("Rel2type field in a rel2type table is not allowed")
  268. #create first a throught model if there is data field associated with the relation
  269. kwargs = dict()
  270. relf_l = f.get_related_fields()
  271. if len(relf_l) > 0:
  272. through_fields = {}
  273. #The two FK of the through model
  274. through_fields[assoc_comp.name] = models.ForeignKey(assoc_comp.uniq_name)
  275. rtype = f.get_related_type()
  276. through_fields[rtype.name] = models.ForeignKey(rtype.uniq_name)
  277. for relf in relf_l:
  278. through_fields[relf.name] = self.field_to_django(relf, None)
  279. #through_model_name = f.uniq_name+assoc_comp.uniq_name+'to'+rtype.uniq_name
  280. through_model_name = f.name + assoc_comp.name + 'to' + rtype.name
  281. module_name = self.app_name + '.models'
  282. #model created
  283. through_model = create_model(through_model_name, through_fields, self.app_name, module_name)
  284. kwargs['through'] = through_model_name
  285. return models.ManyToManyField(f.get_related_type().uniq_name, **kwargs)
  286. else: # Unknow data type
  287. raise NotImplemented("The conversion to django fields is not yet implemented for %s field type" % f.ftype)