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

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