[Mpuls-commits] r4010 - in base/trunk: . mpulsweb/model

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Thu Oct 21 16:07:54 CEST 2010


Author: bh
Date: 2010-10-21 16:07:53 +0200 (Thu, 21 Oct 2010)
New Revision: 4010

Modified:
   base/trunk/ChangeLog
   base/trunk/mpulsweb/model/case.py
Log:
* mpulsweb/model/case.py: Fix formatting.


Modified: base/trunk/ChangeLog
===================================================================
--- base/trunk/ChangeLog	2010-10-21 13:57:43 UTC (rev 4009)
+++ base/trunk/ChangeLog	2010-10-21 14:07:53 UTC (rev 4010)
@@ -1,5 +1,9 @@
 2010-10-21  Bernhard Herzog  <bh at intevation.de>
 
+	* mpulsweb/model/case.py: Fix formatting.
+
+2010-10-21  Bernhard Herzog  <bh at intevation.de>
+
 	* mpulsweb/model/case.py (MpulsCaseBundle.export): Remove an
 	unnecessary exception handler.  The exception handler would handle
 	exceptions that happen during XML serialization by simply loggin

Modified: base/trunk/mpulsweb/model/case.py
===================================================================
--- base/trunk/mpulsweb/model/case.py	2010-10-21 13:57:43 UTC (rev 4009)
+++ base/trunk/mpulsweb/model/case.py	2010-10-21 14:07:53 UTC (rev 4010)
@@ -37,7 +37,8 @@
 from pylons import config
 from mpulsweb.lib.translation import _
 
-from formed.meta.data import RepeatNode, DateLeaf, IntLeaf, TextLeaf, ChoiceNode, RuleLeaf
+from formed.meta.data import RepeatNode, DateLeaf, IntLeaf, TextLeaf,\
+     ChoiceNode, RuleLeaf
 from formed.instance.backends.postgres import DBFactory as InstanceFactory
 from formed.instance.backends.xmlimport import XMLImporter, XMLImportException
 from formed.instance.backends.common import RuleEvalContext
@@ -46,7 +47,7 @@
 from libmpuls.service.tags import TagSetterConfig, TagSetter
 
 from mpulsweb.lib.base import g, h, session
-from mpulsweb.lib.export import XLSExport, CSVExport 
+from mpulsweb.lib.export import XLSExport, CSVExport
 from mpulsweb.lib.anonymize import determineAnonymizedCaseEndPhase
 from mpulsweb.lib.helpers import ensure_unicode, format_date
 from mpulsweb.lib.db import PostgresDBInterface, db
@@ -63,7 +64,11 @@
 log = logging.getLogger(__name__)
 
 
-LOAD_CASE_SQL = """SELECT %(fields)s, ARRAY(SELECT tag_id FROM nm_tags_cases_view WHERE case_id = %%(id)s) AS tags FROM master_tbl_view WHERE id = %%(id)s"""
+LOAD_CASE_SQL = """\
+SELECT
+  %(fields)s,
+  ARRAY(SELECT tag_id FROM nm_tags_cases_view WHERE case_id = %%(id)s) AS tags
+FROM master_tbl_view WHERE id = %%(id)s"""
 
 #SQL
 LOAD_STANDIN_SQL = """
@@ -97,7 +102,8 @@
     SET phase = %(phase)s
     WHERE id IN (SELECT master_id FROM ka_status_tbl_view WHERE id = %(id)s)"""
 ANONYMIZE_CASE = """SELECT anonymize_case_wrapper(%(id)s)"""
-CHECK_REMIND_CONDITION = """select id from master_tbl_view where id = %%(id)s and (%s)"""
+CHECK_REMIND_CONDITION = """\
+SELECT id FROM master_tbl_view WHERE id = %%(id)s AND (%s)"""
 
 #DIALOGS
 MARKANONYMIZE_FAILED_MIN_PHASE = u"""\
@@ -198,7 +204,7 @@
                default caseoverview
 
        info -- If true (default false), the field will be listed in the
-               default infofield 
+               default infofield
 
        info_label --  Defines a label to be used in the infofield.
                Default will be the name of the field.
@@ -246,7 +252,7 @@
                This setting only has an affect if alias is not None.
     """
 
-    def __init__(self, name, digest=False, 
+    def __init__(self, name, digest=False,
                  info=False, info_label=None,
                  search_retrieve=False, search_match=False,
                  session=False, preload=False,
@@ -257,7 +263,7 @@
 
         self.name = name
         self.digest = digest
-        self.info = info 
+        self.info = info
         self.info_label = info_label or name
         self.search_retrieve = search_retrieve
         self.search_match = search_match
@@ -270,7 +276,7 @@
         self.overview = overview
         self.overview_label = overview_label or name
         self.overview_style = overview_style
-        self.overview_length = overview_length 
+        self.overview_length = overview_length
 
     def __repr__(self):
         return "Field(%r)" % (self.name,)
@@ -421,7 +427,7 @@
                 log.exception(e)
         return num
 
-    def export(self, type='XML', anonym=True, selection=None, ):
+    def export(self, type='XML', anonym=True, selection=None):
         factory = InstanceFactory(g.formedTree, PostgresDBInterface())
         num = 0
         xmltree = factory.toXML(self.case_list, selection=selection,
@@ -429,11 +435,11 @@
         num = len(self.case_list)
 
         if type == "XML":
-            export = self._exportXML(xmltree) 
-        elif type== "XLS":
-            export = self._exportXLS(xmltree, selection) 
-        elif type== "CSV":
-            export = self._exportCSV(xmltree, selection) 
+            export = self._exportXML(xmltree)
+        elif type == "XLS":
+            export = self._exportXLS(xmltree, selection)
+        elif type == "CSV":
+            export = self._exportCSV(xmltree, selection)
 
         return num, export
 
@@ -719,7 +725,7 @@
 
     def check_anonymizeability(self, fields=None, phase=None):
         """Raises ConsistenceCheckException if the case is not in a
-        anonymizable state. 
+        anonymizable state.
         """
 
         # 1. Check if anonymisation is allowed in the current phase
@@ -733,29 +739,30 @@
                                   'description')[0].get(phasepart.phase)
         if not phasepart.is_anonymizable():
             raise ConsistenceCheckException(h.literal(MARKANONYMIZE_FAILED_MIN_PHASE
-                                            % desc))
+                                                      % desc))
 
         # 2. Now determine if we will enforce full consistence or minimal
         # consistence (e.g on abort)
         self._load_formed_instance_tree()
-        minimal_condition = g.mpuls_config.get(
-                                'phases', 'minimal_consistence_conditon')
+        minimal_condition = g.mpuls_config.get('phases',
+                                               'minimal_consistence_conditon')
         context = RuleEvalContext(self.formed_instance, "XXX:%s" % self.id)
         minimal_rule = RuleLeaf()
         minimal_rule.setAttribute('expr', minimal_condition)
         if minimal_rule.getExpr().evaluate(context):
             # Also running cases can be anonymized, but check minimal
             # consistence of case for the phase it will be anonymized.
-            min_fields = g.mpuls_config.get('phases', 'minimal_fields_to_anonymize') 
+            min_fields = g.mpuls_config.get('phases',
+                                            'minimal_fields_to_anonymize')
             end_phase = determineAnonymizedCaseEndPhase(self)
             self.check_consistence(min_fields, end_phase)
         else:
             #Check full consistence
             self.check_consistence()
-            # 3. Check if the case is currently running 
+            # 3. Check if the case is currently running
             if isinstance(phasepart, StartPhasePart):
                 raise ConsistenceCheckException(
-                            h.literal(MARKANONYMIZE_FAILED_RUNNING_PHASE % desc))
+                    h.literal(MARKANONYMIZE_FAILED_RUNNING_PHASE % desc))
 
     def make_consistent(self, endphase=None):
         """Will ensure that the case is in a (minimal) consistent state. That
@@ -786,13 +793,14 @@
             if start.date in [None, ""]:
                 key = "%s:%s" % (start.datefield, self.id)
                 data[key] = format_date(datetime.today())
-            if end.date in [None, ""]: 
+            if end.date in [None, ""]:
                 key = "%s:%s" % (end.datefield, self.id)
                 data[key] = format_date(datetime.today())
 
             # Fill all other fields with "unknown" values.
             for field in start.fields:
-                if data.has_key("%s" % (field.id)): continue
+                if data.has_key("%s" % (field.id)):
+                    continue
                 item = self.get_formed_item(field.name)
                 try:
                     value = item.getValue()
@@ -800,13 +808,15 @@
                     if value in [-1, "-1", None, ""]:
                         def_value = get_unknown_value(item)
                         if def_value:
-                            log.debug("Setting %s to %s" % (field.id, def_value))
+                            log.debug("Setting %s to %s"
+                                      % (field.id, def_value))
                             data["%s" % (field.id)] = def_value
                 except:
-                    log.warning('Ups! Tried to get Value from %s which seems to be no field' 
+                    log.warning('Tried to get Value for unknown field %s'
                                 % item.getIdentifier())
             for field in end.fields:
-                if data.has_key("%s" % (field.id)): continue
+                if data.has_key("%s" % (field.id)):
+                    continue
                 try:
                     item = self.get_formed_item(field.name)
                     value = item.getValue()
@@ -814,10 +824,11 @@
                     if item.getValue() in [-1, "-1", None, ""]:
                         def_value = get_unknown_value(item)
                         if def_value:
-                            log.debug("Setting %s to %s" % (field.id, def_value))
+                            log.debug("Setting %s to %s"
+                                      % (field.id, def_value))
                             data["%s" % (field.id)] = def_value
                 except:
-                    log.warning('Ups! Tried to get Value from %s which seems to be no field' 
+                    log.warning('Tried to get Value for unknown field %s'
                                 % item.getIdentifier())
 
         # Set values
@@ -861,10 +872,10 @@
     def getTags(self):
         if self.tags is None:
             self.tags = []
-        return self.tags 
+        return self.tags
 
     def checkValidity(self):
-        '''Will check validity and set tags based on configuration in tagging.xml'''
+        """Check validity and set tags based on configuration in tagging.xml"""
 
         user = session['USER_AUTHORIZED']
         host = config.get('mpuls.db.host')
@@ -874,18 +885,16 @@
         db_name = getDbName()
         filename = config.get('mpuls.app.tagging')
 
-        #TODO: 
+        #TODO:
         # 1. Use established db-connection
         # 2. Do create (and parse config) a TagSetter every time.
 
-        tagconfig = TagSetterConfig(
-            filename, 
-            username=db_user % (db_name, user.login), 
-            password=user.password, 
-            database=db % db_name, 
-            host=host, 
-            port=port, 
-            caseid=self.id)
+        tagconfig = TagSetterConfig(filename,
+                                    username=db_user % (db_name, user.login),
+                                    password=user.password,
+                                    database=db % db_name,
+                                    host=host, port=port,
+                                    caseid=self.id)
         setter = TagSetter(tagconfig)
 
         log.debug('Tagging case: %s' % self.id)
@@ -895,16 +904,16 @@
         '''Will return the id of the max validity based on set tags'''
         tags = set(self.getTags())
         # Try to find the highest validity
-        validity = '0' # Default validity (Not valid) 
+        validity = '0' # Default validity (Not valid)
         for v in g.mpuls_config.get('validities', 'enabled'):
             req_tags = set(v.get('tags', []))
-            if tags.issuperset(req_tags): 
+            if tags.issuperset(req_tags):
                 # case has all requried tags for this validity
                 # -> level up to next validity
                 validity = v.get('id')
             else:
                 break
-        return validity 
+        return validity
 
     def getDocuments(self):
         """Returns a list of documents which are attached to this case"""
@@ -972,6 +981,7 @@
             ps.keepUndefined()
         self.getState().setState(1)
 
+
 class SessionCase:
 
     """This class holds all needed information for the currently selected case
@@ -1074,7 +1084,8 @@
         finally:
             db.recycleConnection(conn, c)
 
-        return self.case_cls(id, preset=self._build_preset(result), tags=result['tags'])
+        return self.case_cls(id, preset=self._build_preset(result),
+                             tags=result['tags'])
 
     def loadFromQueryResult(self, result):
         """Create a Case object from a DB query result row.
@@ -1140,6 +1151,7 @@
         """
         pass
 
+
 class MpulsCaseOverview:
 
     def __init__(self):
@@ -1172,12 +1184,13 @@
         * anonymised (5)
     """
 
-    def __init__(self, id=None, master_id=None, state=None, access=None, phase=None):
+    def __init__(self, id=None, master_id=None, state=None, access=None,
+                 phase=None):
         self.id = id
         self.master_id = master_id
         self.state = state
         self.access = access
-        self.phase = phase 
+        self.phase = phase
         self._last_date = None
 
         if self.master_id is not None and self.id is None:
@@ -1264,7 +1277,7 @@
         desc.append(g.mpuls_config.get('phases',
                                        'description')[0].get(phase.phase))
 
-        # If phase is "unknown" do not append "running/finished" 
+        # If phase is "unknown" do not append "running/finished"
         if phase.id == "-1":
             return " ".join(desc)
         if isinstance(phase, StartPhasePart):
@@ -1292,11 +1305,11 @@
             try:
                 conn = db.getConnection()
                 cur = conn.cursor()
-                sql = CHECK_REMIND_CONDITION % remindercondition 
+                sql = CHECK_REMIND_CONDITION % remindercondition
                 fields = {'id': self.master_id}
                 cur.execute(sql, fields)
                 conn.commit()
-                if cur.fetchone(): 
+                if cur.fetchone():
                     return True
                 return False
             finally:
@@ -1312,14 +1325,14 @@
         else:
             age = datetime.now() - self.getLastDate()
 
-        if self.check_remindcondition(): 
+        if self.check_remindcondition():
             if int(maxage) != 0:
                 return int(maxage) - age.days
         else:
             return 15 # showning counting days until generation of a reminder
                       # starts 14 days before maxsavetime is reached in
                       # template. We do not want such counter until the
-                      # remindcondiotion is not true 
+                      # remindcondiotion is not true
 
 
 



More information about the Mpuls-commits mailing list