Browse Source

Dirty comit of a djago MH that "works"

Code cleaning, commenting etc needed...
Yann Weber 9 years ago
parent
commit
aa6e01bff0

+ 2
- 2
EditorialModel/components.py View File

80
         inited = '_inited' in self.__dict__
80
         inited = '_inited' in self.__dict__
81
         if inited:
81
         if inited:
82
             # if fails raise MigrationHandlerChangeError
82
             # if fails raise MigrationHandlerChangeError
83
-            self.model.migration_handler.register_change(self.uid, {attr_name: getattr(self, attr_name) }, {attr_name: value} )
83
+            self.model.migration_handler.register_change(self.model, self.uid, {attr_name: getattr(self, attr_name) }, {attr_name: value} )
84
         super(EmComponent, self).__setattr__(attr_name, value)
84
         super(EmComponent, self).__setattr__(attr_name, value)
85
         if inited:
85
         if inited:
86
-            self.model.migration_handler.register_model_state(hash(self.model))
86
+            self.model.migration_handler.register_model_state(self.model, hash(self.model))
87
 
87
 
88
     ## Check the type of attribute named var_name
88
     ## Check the type of attribute named var_name
89
     # @param var_name str : the attribute name
89
     # @param var_name str : the attribute name

+ 87
- 10
EditorialModel/migrationhandler/django.py View File

1
 # -*- coding: utf-8 -*-
1
 # -*- coding: utf-8 -*-
2
 
2
 
3
-import django
3
+#from django.conf import settings
4
+#settings.configure(DEBUG=True)
5
+import os
6
+import sys
4
 from django.db import models
7
 from django.db import models
5
-from django.contrib import admin
8
+import django
9
+
10
+from django.db.models.loading import cache as django_cache
11
+from EditorialModel.exceptions import *
12
+
13
+#django.conf.settings.configure(DEBUG=True)
6
 
14
 
7
 ## @package EditorialModel.migrationhandler.django
15
 ## @package EditorialModel.migrationhandler.django
8
 # @brief A migration handler for django ORM
16
 # @brief A migration handler for django ORM
53
 
61
 
54
     app_label = 'lodel'
62
     app_label = 'lodel'
55
 
63
 
56
-    def __init__(self, debug=False):
64
+    ##
65
+    # @param app_name str : The django application name for models generation
66
+    # @param debug bool : Set to True to be in debug mode
67
+    def __init__(self, app_name, debug=False):
68
+        self.models = {}
57
         self.debug = debug
69
         self.debug = debug
58
-
59
-    def register_change(self, uid, initial_state, new_state):
70
+        self.app_name = app_name
71
+    ## @brief Record a change in the EditorialModel and indicate wether or not it is possible to make it
72
+    # @note The states ( initial_state and new_state ) contains only fields that changes
73
+    # @param em model : The EditorialModel.model object to provide the global context
74
+    # @param uid int : The uid of the change EmComponent
75
+    # @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.
76
+    # @param new_state dict | None : dict with field name as key and field value as value. Representing the new state. None mean component deletion
77
+    # @throw EditorialModel.exceptions.MigrationHandlerChangeError if the change was refused
78
+    def register_change(self, em, uid, initial_state, new_state):
79
+
80
+        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Lodel.settings")
81
+        django.setup()
82
+        from django.contrib import admin
83
+        from django.core.management import call_command as django_cmd
84
+
85
+
86
+
87
+        if self.debug:
88
+            print("\n##############")
89
+            print("DummyMigrationHandler debug. Changes for component with uid %d :" % uid)
90
+            if initial_state is None:
91
+                print("Component creation (uid = %d): \n\t" % uid, new_state)
92
+            elif new_state is None:
93
+                print("Component deletion (uid = %d): \n\t" % uid, initial_state)
94
+            else:
95
+                field_list = set(initial_state.keys()).union(set(new_state.keys()))
96
+                for field_name in field_list:
97
+                    str_chg = "\t%s " % field_name
98
+                    if field_name in initial_state:
99
+                        str_chg += "'" + str(initial_state[field_name]) + "'"
100
+                    else:
101
+                        str_chg += " creating "
102
+                    str_chg += " => "
103
+                    if field_name in new_state:
104
+                        str_chg += "'" + str(new_state[field_name]) + "'"
105
+                    else:
106
+                        str_chg += " deletion "
107
+                    print(str_chg)
108
+            print("##############\n")
109
+
110
+        self.em_to_models(em,self.app_name, self.app_name+'models')
111
+        try:
112
+            #ret = django_cmd('makemigrations', self.app_name, interactive=False, noinput=True, dryrun=True, traceback=True)
113
+            #django_cmd('makemigrations', self.app_name, dry-run=True, intercative=True, noinput=True)
114
+            django_cmd('makemigrations', self.app_name, dry_run=True, intercative=True, merge=True, noinput=True)
115
+        except django.core.management.base.CommandError as e:
116
+            raise MigrationHandlerChangeError(str(e))
117
+    
118
+        return True
60
         pass
119
         pass
61
 
120
 
62
-    def register_model_state(self, state_hash):
121
+    def register_model_state(self, em, state_hash):
122
+        print('OHOHOH !!! i\'ve been called')
123
+        #ret = django_cmd('makemigrations', '--noinput', '--traceback', self.app_name)
63
         pass
124
         pass
64
 
125
 
65
     ## @brief Return the models save method
126
     ## @brief Return the models save method
91
     # @todo Handle fieldgroups
152
     # @todo Handle fieldgroups
92
     # @todo write and use a function to forge models name from EmClasses and EmTypes names
153
     # @todo write and use a function to forge models name from EmClasses and EmTypes names
93
     # @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
154
     # @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
94
-    def me_to_models(self, me, app_label, module_name):
155
+    def em_to_models(self, me, app_label, module_name):
156
+        
157
+        #Purging django models cache
158
+        if app_label in django_cache.all_models:
159
+            for modname in django_cache.all_models[app_label]:
160
+                del(django_cache.all_models[app_label][modname])
161
+            #del(django_cache.all_models[app_label])
162
+
163
+        #django_cache.clear_cache()
164
+        del(self.models)
165
+        self.models = {}
166
+
167
+        app_name = self.app_name
95
         #Creating the document model
168
         #Creating the document model
96
         document_attrs = {
169
         document_attrs = {
97
             'lodel_id' : models.AutoField(primary_key=True),
170
             'lodel_id' : models.AutoField(primary_key=True),
123
                 if not emfield.optional:
196
                 if not emfield.optional:
124
                     # !!! Replace with fieldtype 2 django converter
197
                     # !!! Replace with fieldtype 2 django converter
125
                     emclass_fields[emfield.uniq_name] = models.CharField(max_length=56, default=emfield.uniq_name)
198
                     emclass_fields[emfield.uniq_name] = models.CharField(max_length=56, default=emfield.uniq_name)
126
-            print("Model for class %s created with fields : "%emclass.uniq_name, emclass_fields)
199
+            #print("Model for class %s created with fields : "%emclass.uniq_name, emclass_fields)
200
+            print("Model for class %s created"%emclass.uniq_name)
127
             django_models['classes'][emclass.uniq_name] = create_model(emclass.uniq_name, emclass_fields, app_label, module_name, parent_class=django_models['doc'])
201
             django_models['classes'][emclass.uniq_name] = create_model(emclass.uniq_name, emclass_fields, app_label, module_name, parent_class=django_models['doc'])
128
             
202
             
129
             #Creating the EmTypes models with EmClass inherithance
203
             #Creating the EmTypes models with EmClass inherithance
139
                 for nature, superior in emtype.superiors().items():
213
                 for nature, superior in emtype.superiors().items():
140
                     emtype_fields[nature] = models.ForeignKey(superior.uniq_name, related_name=emtype.uniq_name, null=True)
214
                     emtype_fields[nature] = models.ForeignKey(superior.uniq_name, related_name=emtype.uniq_name, null=True)
141
 
215
 
142
-                print("Model for type %s created with fields : "%emtype.uniq_name, emtype_fields)
216
+                #print("Model for type %s created with fields : "%emtype.uniq_name, emtype_fields)
217
+                print("Model for type %s created"%emtype.uniq_name)
143
                 django_models['types'][emtype.uniq_name] = create_model(emtype.uniq_name, emtype_fields, app_label, module_name, parent_class=django_models['classes'][emclass.uniq_name])
218
                 django_models['types'][emtype.uniq_name] = create_model(emtype.uniq_name, emtype_fields, app_label, module_name, parent_class=django_models['classes'][emclass.uniq_name])
144
 
219
 
145
-        return django_models
220
+        self.models=django_models
221
+        pass
222
+
146
 
223
 
147
 
224
 

+ 4
- 3
EditorialModel/migrationhandler/dummy.py View File

14
 
14
 
15
     ## @brief Record a change in the EditorialModel and indicate wether or not it is possible to make it
15
     ## @brief Record a change in the EditorialModel and indicate wether or not it is possible to make it
16
     # @note The states ( initial_state and new_state ) contains only fields that changes
16
     # @note The states ( initial_state and new_state ) contains only fields that changes
17
-    # @param context model : The EditorialModel.model object to provide the global context
17
+    # @param em model : The EditorialModel.model object to provide the global context
18
     # @param uid int : The uid of the change EmComponent
18
     # @param uid int : The uid of the change EmComponent
19
     # @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.
19
     # @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.
20
     # @param new_state dict | None : dict with field name as key and field value as value. Representing the new state. None mean component deletion
20
     # @param new_state dict | None : dict with field name as key and field value as value. Representing the new state. None mean component deletion
21
     # @throw EditorialModel.exceptions.MigrationHandlerChangeError if the change was refused
21
     # @throw EditorialModel.exceptions.MigrationHandlerChangeError if the change was refused
22
-    def register_change(self, uid, initial_state, new_state):
22
+    def register_change(self, em, uid, initial_state, new_state):
23
         if self.debug:
23
         if self.debug:
24
             print("\n##############")
24
             print("\n##############")
25
             print("DummyMigrationHandler debug. Changes for component with uid %d :" % uid)
25
             print("DummyMigrationHandler debug. Changes for component with uid %d :" % uid)
43
                     print(str_chg)
43
                     print(str_chg)
44
             print("##############\n")
44
             print("##############\n")
45
 
45
 
46
-    def register_model_state(self, state_hash):
46
+    ## @brief Not usefull for the moment
47
+    def register_model_state(self, em, state_hash):
47
         if self.debug:
48
         if self.debug:
48
             print("New EditorialModel state registered : '%s'" % state_hash)
49
             print("New EditorialModel state registered : '%s'" % state_hash)

+ 4
- 4
EditorialModel/model.py View File

154
 
154
 
155
         #register the creation in migration handler
155
         #register the creation in migration handler
156
         try:
156
         try:
157
-            self.migration_handler.register_change(em_component.uid, None, em_component.attr_dump)
157
+            self.migration_handler.register_change(self, em_component.uid, None, em_component.attr_dump)
158
         except MigrationHandlerChangeError as exception_object:
158
         except MigrationHandlerChangeError as exception_object:
159
             #Revert the creation
159
             #Revert the creation
160
             self.components(em_component.__class__).remove(em_component)
160
             self.components(em_component.__class__).remove(em_component)
161
             del self._components['uids'][em_component.uid]
161
             del self._components['uids'][em_component.uid]
162
             raise exception_object
162
             raise exception_object
163
 
163
 
164
-        self.migration_handler.register_model_state(hash(self))
164
+        self.migration_handler.register_model_state(self, hash(self))
165
 
165
 
166
         return em_component
166
         return em_component
167
 
167
 
172
     # @todo Handle a raise from the migration handler
172
     # @todo Handle a raise from the migration handler
173
     def delete_component(self, uid):
173
     def delete_component(self, uid):
174
         #register the deletion in migration handler
174
         #register the deletion in migration handler
175
-        self.migration_handler.register_change(uid, self.component(uid).attr_dump, None)
175
+        self.migration_handler.register_change(self, uid, self.component(uid).attr_dump, None)
176
 
176
 
177
         em_component = self.component(uid)
177
         em_component = self.component(uid)
178
         if not em_component:
178
         if not em_component:
181
             self._components[self.name_from_emclass(em_component.__class__)].remove(em_component)
181
             self._components[self.name_from_emclass(em_component.__class__)].remove(em_component)
182
             del self._components['uids'][uid]
182
             del self._components['uids'][uid]
183
         #Register the new EM state
183
         #Register the new EM state
184
-        self.migration_handler.register_model_state(hash(self))
184
+        self.migration_handler.register_model_state(self, hash(self))
185
         return True
185
         return True
186
 
186
 
187
     ## Changes the current backend
187
     ## Changes the current backend

Loading…
Cancel
Save