Browse Source

PEP8 / PyLint on migrationhandler/django.py

Roland Haroutiounian 9 years ago
parent
commit
d378a38bdf
1 changed files with 34 additions and 40 deletions
  1. 34
    40
      EditorialModel/migrationhandler/django.py

+ 34
- 40
EditorialModel/migrationhandler/django.py View File

12
 from EditorialModel.exceptions import *
12
 from EditorialModel.exceptions import *
13
 
13
 
14
 
14
 
15
-
16
 ## @brief Create a django model
15
 ## @brief Create a django model
17
 # @param name str : The django model name
16
 # @param name str : The django model name
18
 # @param fields dict : A dict that contains fields name and type ( str => DjangoField )
17
 # @param fields dict : A dict that contains fields name and type ( str => DjangoField )
39
             setattr(Meta, key, value)
38
             setattr(Meta, key, value)
40
 
39
 
41
     # Set up a dictionary to simulate declarations within a class
40
     # Set up a dictionary to simulate declarations within a class
42
-    attrs = {'__module__': module, 'Meta':Meta}
41
+    attrs = {'__module__': module, 'Meta': Meta}
43
 
42
 
44
     # Add in any fields that were provided
43
     # Add in any fields that were provided
45
     if fields:
44
     if fields:
91
     #
90
     #
92
     # @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
91
     # @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
93
     def register_change(self, em, uid, initial_state, new_state):
92
     def register_change(self, em, uid, initial_state, new_state):
94
-        
93
+
95
         #Starting django
94
         #Starting django
96
         os.environ['LODEL_MIGRATION_HANDLER_TESTS'] = 'YES'
95
         os.environ['LODEL_MIGRATION_HANDLER_TESTS'] = 'YES'
97
         os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Lodel.settings")
96
         os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Lodel.settings")
110
             django_cmd('makemigrations', self.app_name, dry_run=True, interactive=False)
109
             django_cmd('makemigrations', self.app_name, dry_run=True, interactive=False)
111
         except django.core.management.base.CommandError as e:
110
         except django.core.management.base.CommandError as e:
112
             raise MigrationHandlerChangeError(str(e))
111
             raise MigrationHandlerChangeError(str(e))
113
-    
112
+
114
         return True
113
         return True
115
 
114
 
116
     ## @brief Print a debug message representing a migration
115
     ## @brief Print a debug message representing a migration
141
                     print(str_chg)
140
                     print(str_chg)
142
             print("##############\n")
141
             print("##############\n")
143
         pass
142
         pass
144
-    
143
+
145
     ## @brief Register a new model state and update the data representation given the new state
144
     ## @brief Register a new model state and update the data representation given the new state
146
     # @param em model : The EditorialModel to migrate
145
     # @param em model : The EditorialModel to migrate
147
     # @param state_hash str : Note usefull (for the moment ?)
146
     # @param state_hash str : Note usefull (for the moment ?)
171
             #Calling migrate to update the database schema
170
             #Calling migrate to update the database schema
172
             django_cmd('migrate', self.app_name, interactive=False, noinput=True)
171
             django_cmd('migrate', self.app_name, interactive=False, noinput=True)
173
         except django.core.management.base.CommandError as e:
172
         except django.core.management.base.CommandError as e:
174
-            raise MigrationHandlerChangeError("Unable to migrate to new model state : %s"%e)
173
+            raise MigrationHandlerChangeError("Unable to migrate to new model state : %s" % e)
175
 
174
 
176
         pass
175
         pass
177
 
176
 
179
     #
178
     #
180
     # The save function of our class and type models is used to set unconditionnaly the
179
     # The save function of our class and type models is used to set unconditionnaly the
181
     # classtype, class_name and type_name models property
180
     # classtype, class_name and type_name models property
182
-    # 
181
+    #
183
     # @param classname str: The classname used to call the super().save
182
     # @param classname str: The classname used to call the super().save
184
     # @param level str: Wich type of model are we doing. Possible values are 'class' and 'type'
183
     # @param level str: Wich type of model are we doing. Possible values are 'class' and 'type'
185
     # @param datas list : List of property => value to set in the save function
184
     # @param datas list : List of property => value to set in the save function
186
     # @return The wanted save function
185
     # @return The wanted save function
187
     def get_save_fun(self, classname, level, datas):
186
     def get_save_fun(self, classname, level, datas):
188
-        
187
+
189
         if level == 'class':
188
         if level == 'class':
190
             def save(self, *args, **kwargs):
189
             def save(self, *args, **kwargs):
191
                 self.classtype = datas['classtype']
190
                 self.classtype = datas['classtype']
197
                 super(classname, self).save(*args, **kwargs)
196
                 super(classname, self).save(*args, **kwargs)
198
 
197
 
199
         return save
198
         return save
200
-    
199
+
201
     ## @brief Create django models from an EditorialModel.model object
200
     ## @brief Create django models from an EditorialModel.model object
202
     # @param edMod EditorialModel.model.Model : The editorial model instance
201
     # @param edMod EditorialModel.model.Model : The editorial model instance
203
     # @return a dict with all the models
202
     # @return a dict with all the models
205
     # @todo write and use a function to forge models name from EmClasses and EmTypes names
204
     # @todo write and use a function to forge models name from EmClasses and EmTypes names
206
     # @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
205
     # @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
207
     def em_to_models(self, edMod):
206
     def em_to_models(self, edMod):
208
-        
209
-        module_name = self.app_name+'.models'
207
+
208
+        module_name = self.app_name + '.models'
210
 
209
 
211
         #Purging django models cache
210
         #Purging django models cache
212
         if self.app_name in django_cache.all_models:
211
         if self.app_name in django_cache.all_models:
214
                 del(django_cache.all_models[self.app_name][modname])
213
                 del(django_cache.all_models[self.app_name][modname])
215
             #del(django_cache.all_models[self.app_name])
214
             #del(django_cache.all_models[self.app_name])
216
 
215
 
217
-
218
         app_name = self.app_name
216
         app_name = self.app_name
219
         #Creating the document model
217
         #Creating the document model
220
         document_attrs = {
218
         document_attrs = {
221
-            'lodel_id' : models.AutoField(primary_key=True),
219
+            'lodel_id': models.AutoField(primary_key=True),
222
             'classtype': models.CharField(max_length=16, editable=False),
220
             'classtype': models.CharField(max_length=16, editable=False),
223
             'class_name': models.CharField(max_length=16, editable=False),
221
             'class_name': models.CharField(max_length=16, editable=False),
224
             'type_name': models.CharField(max_length=16, editable=False),
222
             'type_name': models.CharField(max_length=16, editable=False),
225
-            'string' : models.CharField(max_length=255),
223
+            'string': models.CharField(max_length=255),
226
             'date_update': models.DateTimeField(auto_now=True, auto_now_add=True),
224
             'date_update': models.DateTimeField(auto_now=True, auto_now_add=True),
227
             'date_create': models.DateTimeField(auto_now_add=True),
225
             'date_create': models.DateTimeField(auto_now_add=True),
228
-            'rank' : models.IntegerField(),
226
+            'rank': models.IntegerField(),
229
             'help_text': models.CharField(max_length=255),
227
             'help_text': models.CharField(max_length=255),
230
         }
228
         }
231
 
229
 
232
         #Creating the base model document
230
         #Creating the base model document
233
         document_model = create_model('document', document_attrs, self.app_name, module_name)
231
         document_model = create_model('document', document_attrs, self.app_name, module_name)
234
 
232
 
235
-        django_models = {'doc' : document_model, 'classes':{}, 'types':{} }
233
+        django_models = {'doc': document_model, 'classes': {}, 'types': {}}
236
 
234
 
237
         classes = edMod.classes()
235
         classes = edMod.classes()
238
 
236
 
239
         #Creating the EmClasses models with document inheritance
237
         #Creating the EmClasses models with document inheritance
240
         for emclass in classes:
238
         for emclass in classes:
241
             emclass_fields = {
239
             emclass_fields = {
242
-                'save' : self.get_save_fun(emclass.uniq_name, 'class', { 'classtype':emclass.classtype, 'class_name':emclass.uniq_name}),
240
+                'save': self.get_save_fun(emclass.uniq_name, 'class', {'classtype': emclass.classtype, 'class_name': emclass.uniq_name}),
243
             }
241
             }
244
 
242
 
245
             #Addding non optionnal fields
243
             #Addding non optionnal fields
250
                     emclass_fields[emfield.uniq_name] = self.field_to_django(emfield, emclass)
248
                     emclass_fields[emfield.uniq_name] = self.field_to_django(emfield, emclass)
251
             #print("Model for class %s created with fields : "%emclass.uniq_name, emclass_fields)
249
             #print("Model for class %s created with fields : "%emclass.uniq_name, emclass_fields)
252
             if self.debug:
250
             if self.debug:
253
-                print("Model for class %s created"%emclass.uniq_name)
251
+                print("Model for class %s created" % emclass.uniq_name)
254
             django_models['classes'][emclass.uniq_name] = create_model(emclass.uniq_name, emclass_fields, self.app_name, module_name, parent_class=django_models['doc'])
252
             django_models['classes'][emclass.uniq_name] = create_model(emclass.uniq_name, emclass_fields, self.app_name, module_name, parent_class=django_models['doc'])
255
-            
253
+
256
             #Creating the EmTypes models with EmClass inherithance
254
             #Creating the EmTypes models with EmClass inherithance
257
             for emtype in emclass.types():
255
             for emtype in emclass.types():
258
                 emtype_fields = {
256
                 emtype_fields = {
259
-                    'save': self.get_save_fun(emtype.uniq_name, 'type', { 'type_name':emtype.uniq_name }),
257
+                    'save': self.get_save_fun(emtype.uniq_name, 'type', {'type_name': emtype.uniq_name}),
260
                 }
258
                 }
261
                 #Adding selected optionnal fields
259
                 #Adding selected optionnal fields
262
                 for emfield in emtype.selected_fields():
260
                 for emfield in emtype.selected_fields():
268
                         emtype_fields[nature] = models.ForeignKey(superior.uniq_name, related_name=emtype.uniq_name, null=True)
266
                         emtype_fields[nature] = models.ForeignKey(superior.uniq_name, related_name=emtype.uniq_name, null=True)
269
 
267
 
270
                 if self.debug:
268
                 if self.debug:
271
-                    print("Model for type %s created"%emtype.uniq_name)
269
+                    print("Model for type %s created" % emtype.uniq_name)
272
                 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])
270
                 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])
273
 
271
 
274
         pass
272
         pass
285
         args['null'] = f.nullable
283
         args['null'] = f.nullable
286
         if not (f.default is None):
284
         if not (f.default is None):
287
             args['default'] = f.default
285
             args['default'] = f.default
288
-        v_fun = f.validation_function(raise_e = ValidationError)
286
+        v_fun = f.validation_function(raise_e=ValidationError)
289
         if v_fun:
287
         if v_fun:
290
             args['validators'] = [v_fun]
288
             args['validators'] = [v_fun]
291
         if f.uniq:
289
         if f.uniq:
292
             args['unique'] = True
290
             args['unique'] = True
293
-        
291
+
294
         # Field instanciation
292
         # Field instanciation
295
-        if f.ftype == 'char': #varchar field
293
+        if f.ftype == 'char':  # varchar field
296
             args['max_length'] = f.max_length
294
             args['max_length'] = f.max_length
297
             return models.CharField(**args)
295
             return models.CharField(**args)
298
-        elif f.ftype == 'int': #integer field
296
+        elif f.ftype == 'int':  # integer field
299
             return models.IntegerField(**args)
297
             return models.IntegerField(**args)
300
-        elif f.ftype == 'text': #text field
298
+        elif f.ftype == 'text':  # text field
301
             return models.TextField(**args)
299
             return models.TextField(**args)
302
-        elif f.ftype == 'datetime': #Datetime field
300
+        elif f.ftype == 'datetime':  # Datetime field
303
             args['auto_now'] = f.now_on_update
301
             args['auto_now'] = f.now_on_update
304
             args['auto_now_add'] = f.now_on_create
302
             args['auto_now_add'] = f.now_on_create
305
             return models.DateTimeField(**args)
303
             return models.DateTimeField(**args)
306
-        elif f.ftype == 'bool': #Boolean field
304
+        elif f.ftype == 'bool':  # Boolean field
307
             if args['null']:
305
             if args['null']:
308
                 return models.NullBooleanField(**args)
306
                 return models.NullBooleanField(**args)
309
             del(args['null'])
307
             del(args['null'])
310
             return models.BooleanField(**args)
308
             return models.BooleanField(**args)
311
-        elif f.ftype == 'rel2type': #Relation to type
309
+        elif f.ftype == 'rel2type':  # Relation to type
312
 
310
 
313
-            if assoc_comp == None:
311
+            if assoc_comp is None:
314
                 raise RuntimeError("Rel2type field in a rel2type table is not allowed")
312
                 raise RuntimeError("Rel2type field in a rel2type table is not allowed")
315
             #create first a throught model if there is data field associated with the relation
313
             #create first a throught model if there is data field associated with the relation
316
             kwargs = dict()
314
             kwargs = dict()
318
             relf_l = f.get_related_fields()
316
             relf_l = f.get_related_fields()
319
             if len(relf_l) > 0:
317
             if len(relf_l) > 0:
320
                 through_fields = {}
318
                 through_fields = {}
321
-                
319
+
322
                 #The two FK of the through model
320
                 #The two FK of the through model
323
                 through_fields[assoc_comp.name] = models.ForeignKey(assoc_comp.uniq_name)
321
                 through_fields[assoc_comp.name] = models.ForeignKey(assoc_comp.uniq_name)
324
                 rtype = f.get_related_type()
322
                 rtype = f.get_related_type()
328
                     through_fields[relf.name] = self.field_to_django(relf, None)
326
                     through_fields[relf.name] = self.field_to_django(relf, None)
329
 
327
 
330
                 #through_model_name = f.uniq_name+assoc_comp.uniq_name+'to'+rtype.uniq_name
328
                 #through_model_name = f.uniq_name+assoc_comp.uniq_name+'to'+rtype.uniq_name
331
-                through_model_name = f.name+assoc_comp.name+'to'+rtype.name
332
-                module_name = self.app_name+'.models'
329
+                through_model_name = f.name + assoc_comp.name + 'to' + rtype.name
330
+                module_name = self.app_name + '.models'
333
                 #model created
331
                 #model created
334
                 through_model = create_model(through_model_name, through_fields, self.app_name, module_name)
332
                 through_model = create_model(through_model_name, through_fields, self.app_name, module_name)
335
                 kwargs['through'] = through_model_name
333
                 kwargs['through'] = through_model_name
336
-            
337
-            return models.ManyToManyField(f.get_related_type().uniq_name, **kwargs)
338
-        else: #Unknow data type
339
-            raise NotImplemented("The conversion to django fields is not yet implemented for %s field type"%f.ftype)
340
-
341
-
342
-        
343
 
334
 
335
+            return models.ManyToManyField(f.get_related_type().uniq_name, **kwargs)
336
+        else:  # Unknow data type
337
+            raise NotImplemented("The conversion to django fields is not yet implemented for %s field type" % f.ftype)

Loading…
Cancel
Save