Browse Source

EmComponent: pep8 et pylint

ArnAud 9 years ago
parent
commit
c95b37df12
1 changed files with 108 additions and 113 deletions
  1. 108
    113
      EditorialModel/components.py

+ 108
- 113
EditorialModel/components.py View File

@@ -5,7 +5,6 @@
5 5
 
6 6
 import datetime
7 7
 
8
-from Lodel.utils.mlstring import MlString
9 8
 import logging
10 9
 import sqlalchemy as sql
11 10
 from Database import sqlutils
@@ -14,6 +13,7 @@ from collections import OrderedDict
14 13
 
15 14
 logger = logging.getLogger('Lodel2.EditorialModel')
16 15
 
16
+
17 17
 ## This class is the mother class of all editorial model objects
18 18
 #
19 19
 # It gather all the properties and mechanism that are common to every editorial model objects
@@ -31,7 +31,7 @@ class EmComponent(object):
31 31
     ranked_in = None
32 32
 
33 33
     ## Read only properties
34
-    _ro_properties = [ 'date_update', 'date_create', 'uid', 'rank', 'deleted']
34
+    _ro_properties = ['date_update', 'date_create', 'uid', 'rank', 'deleted']
35 35
 
36 36
     ## @brief List fields name and fieldtype
37 37
     #
@@ -62,15 +62,15 @@ class EmComponent(object):
62 62
         # Values are handled by EditorialModel::fieldtypes::EmFieldType
63 63
         # @warning \ref _fields instance property is not the same than EmComponent::_fields class property. In the instance property the EditorialModel::fieldtypes::EmFieldType are instanciated to be able to handle datas
64 64
         # @see EmComponent::_fields EditorialModel::fieldtypes::EmFieldType
65
-        self._fields = OrderedDict([ (name, ftype()) for (name,ftype) in (EmComponent._fields + self.__class__._fields) ] )
65
+        self._fields = OrderedDict([(name, ftype()) for (name, ftype) in (EmComponent._fields + self.__class__._fields)])
66 66
 
67 67
         # populate
68 68
         if isinstance(id_or_name, int):
69
-            self._fields['uid'].value = id_or_name #read only propertie set
69
+            self._fields['uid'].value = id_or_name  # read only propertie set
70 70
         elif isinstance(id_or_name, str):
71 71
             self.name = id_or_name
72 72
         else:
73
-            raise TypeError('Bad argument: expecting <int> or <str> but got : '+str(type(id_or_name)))
73
+            raise TypeError('Bad argument: expecting <int> or <str> but got : ' + str(type(id_or_name)))
74 74
         self.table = self.__class__.table
75 75
         self.populate()
76 76
 
@@ -88,7 +88,7 @@ class EmComponent(object):
88 88
     def __getattribute__(self, name):
89 89
         if super(EmComponent, self).__getattribute__('deleted'):
90 90
             #raise EmComponentNotExistError("This component has been deleted")
91
-            raise EmComponentNotExistError("This "+super(EmComponent, self).__getattribute__('__class__').__name__+" has been deleted")
91
+            raise EmComponentNotExistError("This " + super(EmComponent, self).__getattribute__('__class__').__name__ + " has been deleted")
92 92
         res = super(EmComponent, self).__getattribute(name)
93 93
         return res
94 94
 
@@ -96,8 +96,8 @@ class EmComponent(object):
96 96
     # @param name str: The propertie name
97 97
     # @param value *: The value
98 98
     def __setattr__(self, name, value):
99
-        if name in  self.__class__._ro_properties:
100
-            raise TypeError("Propertie '"+name+"' is readonly")
99
+        if name in self.__class__._ro_properties:
100
+            raise TypeError("Propertie '" + name + "' is readonly")
101 101
 
102 102
         if name != '_fields' and hasattr(self, '_fields') and name in object.__getattribute__(self, '_fields'):
103 103
             self._fields[name].from_python(value)
@@ -107,7 +107,7 @@ class EmComponent(object):
107 107
     ## Lookup in the database properties of the object to populate the properties
108 108
     # @throw EmComponentNotExistError if the instance is not anymore stored in database
109 109
     def populate(self):
110
-        records = self._populateDb() #Db query
110
+        records = self._populate_db()  # Db query
111 111
 
112 112
         for record in records:
113 113
             for keys in self._fields.keys():
@@ -118,28 +118,28 @@ class EmComponent(object):
118 118
 
119 119
     @classmethod
120 120
     ## Shortcut that return the sqlAlchemy engine
121
-    def getDbE(c):
122
-        return sqlutils.getEngine(c.dbconf)
123
-    
121
+    def getDbE(cls):
122
+        return sqlutils.getEngine(cls.dbconf)
123
+
124 124
     ## Do the query on the database for EmComponent::populate()
125 125
     # @throw EmComponentNotExistError if the instance is not anymore stored in database
126
-    def _populateDb(self):
126
+    def _populate_db(self):
127 127
         dbe = self.__class__.getDbE()
128 128
         component = sql.Table(self.table, sqlutils.meta(dbe))
129 129
         req = sql.sql.select([component])
130 130
 
131
-        if self.uid == None:
131
+        if self.uid is None:
132 132
             req = req.where(component.c.name == self.name)
133 133
         else:
134 134
             req = req.where(component.c.uid == self.uid)
135
-        c = dbe.connect()
136
-        res = c.execute(req)
135
+        conn = dbe.connect()
136
+        res = conn.execute(req)
137 137
 
138 138
         res = res.fetchall()
139
-        c.close()
139
+        conn.close()
140 140
 
141 141
         if not res or len(res) == 0:
142
-            raise EmComponentNotExistError("No "+self.__class__.__name__+" found with "+('name ' + self.name if self.uid == None else 'uid ' + str(self.uid) ))
142
+            raise EmComponentNotExistError("No " + self.__class__.__name__ + " found with " + ('name ' + self.name if self.uid is None else 'uid ' + str(self.uid)))
143 143
 
144 144
         return res
145 145
 
@@ -156,30 +156,29 @@ class EmComponent(object):
156 156
     # @todo Put a real rank at creation
157 157
     # @todo Stop using datetime.datetime.utcnow() for date_update and date_create init
158 158
     @classmethod
159
-    def create(cl, **kwargs):
159
+    def create(cls, **kwargs):
160 160
         for argname in kwargs:
161
-            if argname in ['date_update', 'date_create', 'rank', 'uid']: #Automatic properties
162
-                raise TypeError("Invalid argument : "+argname)
161
+            if argname in ['date_update', 'date_create', 'rank', 'uid']:  # Automatic properties
162
+                raise TypeError("Invalid argument : " + argname)
163 163
 
164 164
         #TODO check that every mandatory _fields are here like below for example
165
-        #for name in cl._fields:
166
-        #    if cl._fields[name].notNull and cl._fields[name].default == None:
165
+        #for name in cls._fields:
166
+        #    if cls._fields[name].notNull and cls._fields[name].default == None:
167 167
         #        raise TypeError("Missing argument : "+name)
168 168
 
169
-        kwargs['uid'] = cl.newUid()
169
+        kwargs['uid'] = cls.new_uid()
170 170
         kwargs['date_update'] = kwargs['date_create'] = datetime.datetime.utcnow()
171 171
 
172
-        dbe = cl.getDbE()
172
+        dbe = cls.getDbE()
173 173
         conn = dbe.connect()
174 174
 
175
-        kwargs['rank'] = -1 #Warning !!!
175
+        kwargs['rank'] = -1  # Warning !!!
176 176
 
177
-        table = sql.Table(cl.table, sqlutils.meta(dbe))
177
+        table = sql.Table(cls.table, sqlutils.meta(dbe))
178 178
         req = table.insert(kwargs)
179
-        res = conn.execute(req) #Check res?
179
+        conn.execute(req)  # Check ?
180 180
         conn.close()
181
-        return cl(kwargs['name']) #Maybe no need to check res because this would fail if the query failed
182
-
181
+        return cls(kwargs['name'])  # Maybe no need to check res because this would fail if the query failed
183 182
 
184 183
     ## Write the representation of the component in the database
185 184
     # @return bool
@@ -189,32 +188,30 @@ class EmComponent(object):
189 188
         for name, field in self._fields.items():
190 189
             values[name] = field.to_sql()
191 190
 
192
-        #Don't allow creation date overwritting
193
-        """
194
-        if 'date_create' in values:
195
-            del values['date_create']
196
-            logger.warning("date_create supplied for save, but overwritting of date_create not allowed, the date will not be changed")
197
-        """
191
+        # Don't allow creation date overwritting
192
+        #if 'date_create' in values:
193
+            #del values['date_create']
194
+            #logger.warning("date_create supplied for save, but overwritting of date_create not allowed, the date will not be changed")
195
+
198 196
         values['date_update'] = datetime.datetime.utcnow()
199 197
 
200
-        self._saveDb(values)
201
-    
198
+        self._save_db(values)
199
+
202 200
     ## Do the query in the datbase for EmComponent::save()
203 201
     # @param values dict: A dictionnary of the values to insert
204 202
     # @throw RunTimeError if it was unable to do the Db update
205
-    def _saveDb(self, values):
203
+    def _save_db(self, values):
206 204
         """ Do the query on the db """
207 205
         dbe = self.__class__.getDbE()
208 206
         component = sql.Table(self.table, sqlutils.meta(dbe))
209
-        req = sql.update(component, values = values).where(component.c.uid == self.uid)
207
+        req = sql.update(component, values=values).where(component.c.uid == self.uid)
210 208
 
211
-        c = dbe.connect()
212
-        res = c.execute(req)
213
-        c.close()
209
+        conn = dbe.connect()
210
+        res = conn.execute(req)
211
+        conn.close()
214 212
         if not res:
215 213
             raise RuntimeError("Unable to save the component in the database")
216 214
 
217
-
218 215
     ## Delete this component data in the database
219 216
     # @return bool
220 217
     # @todo Use something like __del__ instead (or call it at the end)
@@ -223,16 +220,15 @@ class EmComponent(object):
223 220
         #<SQL>
224 221
         dbe = self.__class__.getDbE()
225 222
         component = sql.Table(self.table, sqlutils.meta(dbe))
226
-        req= component.delete().where(component.c.uid == self.uid)
227
-        c = dbe.connect()
228
-        res = c.execute(req)
229
-        c.close
223
+        req = component.delete().where(component.c.uid == self.uid)
224
+        conn = dbe.connect()
225
+        res = conn.execute(req)
226
+        conn.close()
230 227
         if not res:
231 228
             raise RuntimeError("Unable to delete the component in the database")
232 229
 
233 230
         super(EmComponent, self).__setattr__('deleted', True)
234 231
         #</SQL>
235
-        pass
236 232
 
237 233
     ## get_max_rank
238 234
     # Retourne le rank le plus élevé pour le groupe de component au quel apartient l'objet actuelle
@@ -241,12 +237,12 @@ class EmComponent(object):
241 237
         dbe = self.__class__.getDbE()
242 238
         component = sql.Table(self.table, sqlutils.meta(dbe))
243 239
         req = sql.sql.select([component.c.rank]).where(getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)).order_by(component.c.rank.desc())
244
-        c = dbe.connect()
245
-        res = c.execute(req)
240
+        conn = dbe.connect()
241
+        res = conn.execute(req)
246 242
         res = res.fetchone()
247
-        c.close()
243
+        conn.close()
248 244
 
249
-        if(res != None):
245
+        if (res is not None):
250 246
             return res['rank']
251 247
         else:
252 248
             return -1
@@ -263,129 +259,126 @@ class EmComponent(object):
263 259
     # @return bool: True en cas de réussite False en cas d'echec.
264 260
     # @throw TypeError if an argument isn't from the expected type
265 261
     # @thrown ValueError if an argument as a wrong value but is of the good type
266
-    def modify_rank(self, new_rank, sign = '='):
262
+    def modify_rank(self, new_rank, sign='='):
267 263
 
268
-        if(type(new_rank) is int):
269
-            if(new_rank >= 0):
264
+        if (type(new_rank) is int):
265
+            if (new_rank >= 0):
270 266
                 dbe = self.__class__.getDbE()
271 267
                 component = sql.Table(self.table, sqlutils.meta(dbe))
272 268
                 req = sql.sql.select([component.c.uid, component.c.rank])
273 269
 
274
-                if(type(sign) is not str):
270
+                if (type(sign) is not str):
275 271
                     logger.error("Bad argument")
276
-                    raise TypeError('Excepted a string (\'=\' or \'+\' or \'-\') not a '+str(type(sign)))
277
-
278
-                if(sign == '='):
272
+                    raise TypeError('Excepted a string (\'=\' or \'+\' or \'-\') not a ' + str(type(sign)))
279 273
 
274
+                if (sign == '='):
280 275
                     req = sql.sql.select([component.c.uid, component.c.rank])
281 276
                     req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank == new_rank))
282
-                    c = dbe.connect()
283
-                    res = c.execute(req)
277
+                    conn = dbe.connect()
278
+                    res = conn.execute(req)
284 279
                     res = res.fetchone()
285
-                    c.close()
280
+                    conn.close()
286 281
 
287
-                    if(res != None):
282
+                    if (res is not None):
288 283
                         req = sql.sql.select([component.c.uid, component.c.rank])
289 284
                         if(new_rank < self.rank):
290
-                            req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & ( component.c.rank >= new_rank) & (component.c.rank < self.rank))
285
+                            req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank >= new_rank) & (component.c.rank < self.rank))
291 286
                         else:
292 287
                             req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank <= new_rank) & (component.c.rank > self.rank))
293 288
 
294
-                        c = dbe.connect()
295
-                        res = c.execute(req)
289
+                        conn = dbe.connect()
290
+                        res = conn.execute(req)
296 291
                         res = res.fetchall()
297 292
 
298 293
                         vals = list()
299
-                        vals.append({'id' : self.uid, 'rank' : new_rank})
294
+                        vals.append({'id': self.uid, 'rank': new_rank})
300 295
 
301 296
                         for row in res:
302 297
                             if(new_rank < self.rank):
303
-                                vals.append({'id' : row.uid, 'rank' : row.rank+1})
298
+                                vals.append({'id': row.uid, 'rank': row.rank + 1})
304 299
                             else:
305
-                                vals.append({'id' : row.uid, 'rank' : row.rank-1})
300
+                                vals.append({'id': row.uid, 'rank': row.rank - 1})
306 301
 
307
-
308
-                        req = component.update().where(component.c.uid == sql.bindparam('id')).values(rank = sql.bindparam('rank'))
309
-                        c.execute(req, vals)
310
-                        c.close()
302
+                        req = component.update().where(component.c.uid == sql.bindparam('id')).values(rank=sql.bindparam('rank'))
303
+                        conn.execute(req, vals)
304
+                        conn.close()
311 305
 
312 306
                         self._fields['rank'].value = new_rank
313 307
 
314 308
                     else:
315 309
                         logger.error("Bad argument")
316
-                        raise ValueError('new_rank to big, new_rank - 1 doesn\'t exist. new_rank = '+str((new_rank)))
317
-                elif(sign == '+' and self.rank + new_rank <= self.get_max_rank()):
310
+                        raise ValueError('new_rank to big, new_rank - 1 doesn\'t exist. new_rank = ' + str((new_rank)))
311
+                elif (sign == '+' and self.rank + new_rank <= self.get_max_rank()):
318 312
                     req = sql.sql.select([component.c.uid, component.c.rank])
319 313
                     req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank == self.rank + new_rank))
320
-                    c = dbe.connect()
321
-                    res = c.execute(req)
314
+                    conn = dbe.connect()
315
+                    res = conn.execute(req)
322 316
                     res = res.fetchone()
323
-                    c.close()
317
+                    conn.close()
324 318
 
325
-                    if(res != None):
326
-                        if(new_rank != 0):
319
+                    if (res is not None):
320
+                        if (new_rank != 0):
327 321
                             req = sql.sql.select([component.c.uid, component.c.rank])
328 322
                             req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank <= self.rank + new_rank) & (component.c.rank > self.rank))
329 323
 
330
-                            c = dbe.connect()
331
-                            res = c.execute(req)
324
+                            conn = dbe.connect()
325
+                            res = conn.execute(req)
332 326
                             res = res.fetchall()
333 327
 
334 328
                             vals = list()
335
-                            vals.append({'id' : self.uid, 'rank' : self.rank + new_rank})
329
+                            vals.append({'id': self.uid, 'rank': self.rank + new_rank})
336 330
 
337 331
                             for row in res:
338
-                                vals.append({'id' : row.uid, 'rank' : row.rank - 1})
332
+                                vals.append({'id': row.uid, 'rank': row.rank - 1})
333
+
334
+                            req = component.update().where(component.c.uid == sql.bindparam('id')).values(rank=sql.bindparam('rank'))
335
+                            conn.execute(req, vals)
336
+                            conn.close()
339 337
 
340
-                            req = component.update().where(component.c.uid == sql.bindparam('id')).values(rank = sql.bindparam('rank'))
341
-                            c.execute(req, vals)
342
-                            c.close()
343
-                            
344 338
                             self._fields['rank'] += new_rank
345 339
                         else:
346 340
                             logger.error("Bad argument")
347
-                            raise ValueError('Excepted a positive int not a null. new_rank = '+str((new_rank)))
341
+                            raise ValueError('Excepted a positive int not a null. new_rank = ' + str((new_rank)))
348 342
                     else:
349 343
                         logger.error("Bad argument")
350
-                        raise ValueError('new_rank to big, rank + new rank doesn\'t exist. new_rank = '+str((new_rank)))
351
-                elif(sign == '-' and self.rank - new_rank >= 0):
352
-                    if((self.rank + new_rank) > 0):
353
-                        if(new_rank != 0):
344
+                        raise ValueError('new_rank to big, rank + new rank doesn\'t exist. new_rank = ' + str((new_rank)))
345
+                elif (sign == '-' and self.rank - new_rank >= 0):
346
+                    if ((self.rank + new_rank) > 0):
347
+                        if (new_rank != 0):
354 348
                             req = sql.sql.select([component.c.uid, component.c.rank])
355 349
                             req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank >= self.rank - new_rank) & (component.c.rank < self.rank))
356 350
 
357
-                            c = dbe.connect()
358
-                            res = c.execute(req)
351
+                            conn = dbe.connect()
352
+                            res = conn.execute(req)
359 353
                             res = res.fetchall()
360 354
 
361 355
                             vals = list()
362
-                            vals.append({'id' : self.uid, 'rank' : self.rank - new_rank})
356
+                            vals.append({'id': self.uid, 'rank': self.rank - new_rank})
363 357
 
364 358
                             for row in res:
365
-                                vals.append({'id' : row.uid, 'rank' : row.rank + 1})
359
+                                vals.append({'id': row.uid, 'rank': row.rank + 1})
366 360
 
367
-                            req = component.update().where(component.c.uid == sql.bindparam('id')).values(rank = sql.bindparam('rank'))
368
-                            c.execute(req, vals)
369
-                            c.close()
361
+                            req = component.update().where(component.c.uid == sql.bindparam('id')).values(rank=sql.bindparam('rank'))
362
+                            conn.execute(req, vals)
363
+                            conn.close()
370 364
 
371 365
                             self._fields['rank'] -= new_rank
372 366
                         else:
373 367
                             logger.error("Bad argument")
374
-                            raise ValueError('Excepted a positive int not a null. new_rank = '+str((new_rank)))
368
+                            raise ValueError('Excepted a positive int not a null. new_rank = ' + str((new_rank)))
375 369
                     else:
376 370
                         logger.error("Bad argument")
377
-                        raise ValueError('new_rank to big, rank - new rank is negative. new_rank = '+str((new_rank)))
371
+                        raise ValueError('new_rank to big, rank - new rank is negative. new_rank = ' + str((new_rank)))
378 372
                 else:
379 373
                     logger.error("Bad argument")
380
-                    raise ValueError('Excepted a string (\'=\' or \'+\' or \'-\') not a '+str((sign)))
374
+                    raise ValueError('Excepted a string (\'=\' or \'+\' or \'-\') not a ' + str((sign)))
381 375
 
382 376
             else:
383 377
                 logger.error("Bad argument")
384
-                raise ValueError('Excepted a positive int not a negative. new_rank = '+str((new_rank)))
378
+                raise ValueError('Excepted a positive int not a negative. new_rank = ' + str((new_rank)))
385 379
         else:
386 380
             logger.error("Bad argument")
387
-            raise TypeError('Excepted a int not a '+str(type(new_rank)))
388
-
381
+            raise TypeError('Excepted a int not a ' + str(type(new_rank)))
389 382
 
390 383
     def __repr__(self):
391 384
         if self.name is None:
@@ -395,31 +388,33 @@ class EmComponent(object):
395 388
 
396 389
     @classmethod
397 390
     ## Register a new component in UID table
398
-    # 
391
+    #
399 392
     # Use the class property table
400 393
     # @return A new uid (an integer)
401
-    def newUid(cl):
402
-        if cl.table == None:
394
+    def new_uid(cls):
395
+        if cls.table is None:
403 396
             raise NotImplementedError("Abstract method")
404 397
 
405
-        dbe = cl.getDbE()
398
+        dbe = cls.getDbE()
406 399
 
407 400
         uidtable = sql.Table('uids', sqlutils.meta(dbe))
408 401
         conn = dbe.connect()
409
-        req = uidtable.insert(values={'table':cl.table})
402
+        req = uidtable.insert(values={'table': cls.table})
410 403
         res = conn.execute(req)
411 404
 
412 405
         uid = res.inserted_primary_key[0]
413
-        logger.debug("Registering a new UID '"+str(uid)+"' for '"+cl.table+"' component")
406
+        logger.debug("Registering a new UID '" + str(uid) + "' for '" + cls.table + "' component")
414 407
 
415 408
         conn.close()
416 409
 
417 410
         return uid
418 411
 
412
+
419 413
 ## An exception class to tell that a component don't exist
420 414
 class EmComponentNotExistError(Exception):
421 415
     pass
422 416
 
417
+
423 418
 ## An exception class to tell that no ranking exist yet for the group of the object
424 419
 class EmComponentRankingNotExistError(Exception):
425 420
     pass

Loading…
Cancel
Save