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. #from django.conf import settings
  3. #settings.configure(DEBUG=True)
  4. import os
  5. import sys
  6. import django
  7. from django.db import models
  8. from django.db.models.loading import cache as django_cache
  9. from django.core.exceptions import ValidationError
  10. from EditorialModel.exceptions import *
  11. #django.conf.settings.configure(DEBUG=True)
  12. ## @brief Create a django model
  13. # @param name str : The django model name
  14. # @param fields dict : A dict that contains fields name and type ( str => DjangoField )
  15. # @param app_label str : The name of the applications that will have those models
  16. # @param module str : The module name this model will belong to
  17. # @param options dict : Dict of options (name => value)
  18. # @param admin_opts dict : Dict of options for admin part of this model
  19. # @param parent_class str : Parent class name
  20. # @return A dynamically created django model
  21. # @source https://code.djangoproject.com/wiki/DynamicModels
  22. #
  23. def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None, parent_class=None):
  24. class Meta:
  25. # Using type('Meta', ...) gives a dictproxy error during model creation
  26. pass
  27. if app_label:
  28. # app_label must be set using the Meta inner class
  29. setattr(Meta, 'app_label', app_label)
  30. # Update Meta with any options that were provided
  31. if options is not None:
  32. for key, value in options.iteritems():
  33. setattr(Meta, key, value)
  34. # Set up a dictionary to simulate declarations within a class
  35. attrs = {'__module__': module, 'Meta':Meta}
  36. # Add in any fields that were provided
  37. if fields:
  38. attrs.update(fields)
  39. # Create the class, which automatically triggers ModelBase processing
  40. if parent_class is None:
  41. parent_class = models.Model
  42. model = type(name, (parent_class,), attrs)
  43. # Create an Admin class if admin options were provided
  44. if admin_opts is not None:
  45. class Admin(admin.ModelAdmin):
  46. pass
  47. for key, value in admin_opts:
  48. setattr(Admin, key, value)
  49. admin.site.register(model, Admin)
  50. return model
  51. ## @package EditorialModel.migrationhandler.django
  52. # @brief A migration handler for django ORM
  53. #
  54. # Create django models according to the editorial model
  55. class DjangoMigrationHandler(object):
  56. ##
  57. # @param app_name str : The django application name for models generation
  58. # @param debug bool : Set to True to be in debug mode
  59. # @warning DONT use self.models it does not contains all the models (none of the through models for rel2type)
  60. def __init__(self, app_name, debug=False, dryrun=False):
  61. self.models = {}
  62. self.debug = debug
  63. self.app_name = app_name
  64. self.dryrun = dryrun
  65. ## @brief Record a change in the EditorialModel and indicate wether or not it is possible to make it
  66. # @note The states ( initial_state and new_state ) contains only fields that changes
  67. #
  68. # @note Migration is not applied by this method. This method only checks if the new em is valid
  69. #
  70. # @param em model : The EditorialModel.model object to provide the global context
  71. # @param uid int : The uid of the change EmComponent
  72. # @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.
  73. # @param new_state dict | None : dict with field name as key and field value as value. Representing the new state. None mean component deletion
  74. # @throw EditorialModel.exceptions.MigrationHandlerChangeError if the change was refused
  75. # @todo Some tests about strating django in this method
  76. # @todo Rename in something like "validate_change"
  77. #
  78. # @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
  79. def register_change(self, em, uid, initial_state, new_state):
  80. #Starting django
  81. os.environ['LODEL_MIGRATION_HANDLER_TESTS'] = 'YES'
  82. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Lodel.settings")
  83. django.setup()
  84. from django.contrib import admin
  85. from django.core.management import call_command as django_cmd
  86. if self.debug:
  87. self.dump_migration(uid, initial_state, new_state)
  88. #Generation django models
  89. self.em_to_models(em)
  90. try:
  91. #Calling makemigrations to see if the migration is valid
  92. #django_cmd('makemigrations', self.app_name, dry_run=True, interactive=False, merge=True)
  93. django_cmd('makemigrations', self.app_name, dry_run=True, interactive=False)
  94. except django.core.management.base.CommandError as e:
  95. raise MigrationHandlerChangeError(str(e))
  96. return True
  97. ## @brief Print a debug message representing a migration
  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. #This cache at instance level seems to be useless...
  184. del(self.models)
  185. self.models = {}
  186. app_name = self.app_name
  187. #Creating the document model
  188. document_attrs = {
  189. 'lodel_id' : models.AutoField(primary_key=True),
  190. 'classtype': models.CharField(max_length=16, editable=False),
  191. 'class_name': models.CharField(max_length=16, editable=False),
  192. 'type_name': models.CharField(max_length=16, editable=False),
  193. 'string' : models.CharField(max_length=255),
  194. 'date_update': models.DateTimeField(auto_now=True, auto_now_add=True),
  195. 'date_create': models.DateTimeField(auto_now_add=True),
  196. 'rank' : models.IntegerField(),
  197. 'help_text': models.CharField(max_length=255),
  198. }
  199. #Creating the base model document
  200. document_model = create_model('document', document_attrs, self.app_name, module_name)
  201. django_models = {'doc' : document_model, 'classes':{}, 'types':{} }
  202. classes = edMod.classes()
  203. #Creating the EmClasses models with document inheritance
  204. for emclass in classes:
  205. emclass_fields = {
  206. 'save' : self.get_save_fun(emclass.uniq_name, 'class', { 'classtype':emclass.classtype, 'class_name':emclass.uniq_name}),
  207. }
  208. #Addding non optionnal fields
  209. for emfield in emclass.fields():
  210. if not emfield.optional:
  211. # !!! Replace with fieldtype 2 django converter
  212. #emclass_fields[emfield.uniq_name] = models.CharField(max_length=56, default=emfield.uniq_name)
  213. emclass_fields[emfield.uniq_name] = self.field_to_django(emfield, emclass)
  214. #print("Model for class %s created with fields : "%emclass.uniq_name, emclass_fields)
  215. print("Model for class %s created"%emclass.uniq_name)
  216. django_models['classes'][emclass.uniq_name] = create_model(emclass.uniq_name, emclass_fields, self.app_name, module_name, parent_class=django_models['doc'])
  217. #Creating the EmTypes models with EmClass inherithance
  218. for emtype in emclass.types():
  219. emtype_fields = {
  220. 'save': self.get_save_fun(emtype.uniq_name, 'type', { 'type_name':emtype.uniq_name }),
  221. }
  222. #Adding selected optionnal fields
  223. for emfield in emtype.selected_fields():
  224. #emtype_fields[emfield.uniq_name] = models.CharField(max_length=56, default=emfield.uniq_name)
  225. emtype_fields[emfield.uniq_name] = self.field_to_django(emfield, emtype)
  226. #Adding superiors foreign key
  227. for nature, superior in emtype.superiors().items():
  228. emtype_fields[nature] = models.ForeignKey(superior.uniq_name, related_name=emtype.uniq_name, null=True)
  229. if self.debug:
  230. print("Model for type %s created"%emtype.uniq_name)
  231. 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])
  232. self.models=django_models
  233. pass
  234. ## @brief Return a good django field type given a field
  235. # @param f EmField : an EmField object
  236. # @param assoc_comp EmComponent : The associated component (type or class)
  237. # @return A django field instance
  238. # @note The manytomany fields created with the rel2type field has no related_name associated to it
  239. def field_to_django(self, f, assoc_comp):
  240. #Building the args dictionnary for django field instanciation
  241. args = dict()
  242. args['null'] = f.nullable
  243. if not (f.default is None):
  244. args['default'] = f.default
  245. v_fun = f.validation_function(raise_e = ValidationError)
  246. if v_fun:
  247. args['validators'] = [v_fun]
  248. if f.uniq:
  249. args['unique'] = True
  250. # Field instanciation
  251. if f.ftype == 'char': #varchar field
  252. args['max_length'] = f.max_length
  253. return models.CharField(**args)
  254. elif f.ftype == 'int': #integer field
  255. return models.IntegerField(**args)
  256. elif f.ftype == 'text': #text field
  257. return models.TextField(**args)
  258. elif f.ftype == 'datetime': #Datetime field
  259. args['auto_now'] = f.now_on_update
  260. args['auto_now_add'] = f.now_on_create
  261. return models.DateTimeField(**args)
  262. elif f.ftype == 'rel2type': #Relation to type
  263. if assoc_comp == None:
  264. raise RuntimeError("Rel2type field in a rel2type table is not allowed")
  265. #create first a throught model if there is data field associated with the relation
  266. kwargs = dict()
  267. relf_l = f.get_related_fields()
  268. if len(relf_l) > 0:
  269. through_fields = {}
  270. #The two FK of the through model
  271. through_fields[assoc_comp.name] = models.ForeignKey(assoc_comp.uniq_name)
  272. rtype = f.get_related_type()
  273. through_fields[rtype.name] = models.ForeignKey(rtype.uniq_name)
  274. for relf in relf_l:
  275. through_fields[relf.name] = self.field_to_django(relf, None)
  276. #through_model_name = f.uniq_name+assoc_comp.uniq_name+'to'+rtype.uniq_name
  277. through_model_name = f.name+assoc_comp.name+'to'+rtype.name
  278. module_name = self.app_name+'models'
  279. #model created
  280. through_model = create_model(through_model_name, through_fields, self.app_name, module_name)
  281. kwargs['through'] = through_model_name
  282. print('WOW !')
  283. return models.ManyToManyField(f.get_related_type().uniq_name, **kwargs)
  284. else:
  285. raise NotImplemented("The conversion to django fields is not yet implemented for %s field type"%f.ftype)