[Mpuls-commits] r1678 - in wasko/branches/2.0: . mpulsweb/model waskaweb/model

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Mon Feb 22 17:51:22 CET 2010


Author: bh
Date: 2010-02-22 17:51:21 +0100 (Mon, 22 Feb 2010)
New Revision: 1678

Modified:
   wasko/branches/2.0/ChangeLog
   wasko/branches/2.0/mpulsweb/model/case.py
   wasko/branches/2.0/waskaweb/model/case.py
Log:
* mpulsweb/model/case.py (LOAD_CASE_SQL, MpulsCaseFactory): Moved
here from waskaweb/model/case.py.  MpulsCaseFactory is the MPuls
base class for case factories.

* waskaweb/model/case.py (CaseFactory): Derive from
MpulsCaseFactory.  All methods except _initNewCase are in the base
class now.
(LOAD_CASE_SQL): Removed.  Moved to mpulsweb/model/case.py


Modified: wasko/branches/2.0/ChangeLog
===================================================================
--- wasko/branches/2.0/ChangeLog	2010-02-22 16:06:38 UTC (rev 1677)
+++ wasko/branches/2.0/ChangeLog	2010-02-22 16:51:21 UTC (rev 1678)
@@ -1,5 +1,18 @@
 2010-02-22  Bernhard Herzog  <bh at intevation.de>
 
+	Move most of the CaseFactory to mpulsweb:
+
+	* mpulsweb/model/case.py (LOAD_CASE_SQL, MpulsCaseFactory): Moved
+	here from waskaweb/model/case.py.  MpulsCaseFactory is the MPuls
+	base class for case factories.
+
+	* waskaweb/model/case.py (CaseFactory): Derive from
+	MpulsCaseFactory.  All methods except _initNewCase are in the base
+	class now.
+	(LOAD_CASE_SQL): Removed.  Moved to mpulsweb/model/case.py
+
+2010-02-22  Bernhard Herzog  <bh at intevation.de>
+
 	* waskaweb/model/case.py (CaseFactory._updateMasterOnCreate):
 	Simplify exception handling.  The SetDataException is still
 	caught, though, but it's logged at least.

Modified: wasko/branches/2.0/mpulsweb/model/case.py
===================================================================
--- wasko/branches/2.0/mpulsweb/model/case.py	2010-02-22 16:06:38 UTC (rev 1677)
+++ wasko/branches/2.0/mpulsweb/model/case.py	2010-02-22 16:51:21 UTC (rev 1678)
@@ -29,17 +29,25 @@
 
 import logging
 
+import psycopg2.extras
+
 from formed.meta.data import RepeatNode
 from formed.instance.backends.postgres import DBFactory as InstanceFactory
+from formed.instance.tree import SetDataException
 
-from mpulsweb.lib.base import g
+from mpulsweb.lib.base import g, session
 from mpulsweb.lib.helpers import ensure_unicode
-from mpulsweb.lib.db import PostgresDBInterface
+from mpulsweb.lib.db import PostgresDBInterface, db
 
+from mpulsweb.controllers.formularpage import convert2dic
 
+
 log = logging.getLogger(__name__)
 
 
+LOAD_CASE_SQL = """SELECT %(fields)s FROM master_tbl_view WHERE id = %%(id)s"""
+
+
 class LoadCaseNotExistsError(Exception):
 
     def __init__(self, value):
@@ -283,3 +291,119 @@
         if fid:
             return self.formed_instance.getItem(fid)
         return None
+
+
+class MpulsCaseFactory:
+
+    """Factory for case object. This factory provides methods to either load
+    existing cases from db or create new cases"""
+
+    def __init__(self, case_cls=None):
+        if case_cls is None:
+            case_cls = Case
+        self.case_cls = case_cls
+
+    def get_search_retrieve_fields(self):
+        """Frontend for the same method of the factory's case class"""
+        return self.case_cls.get_search_retrieve_fields()
+
+    def get_search_match_fields(self):
+        """Frontend for the same method of the factory's case class"""
+        return self.case_cls.get_search_match_fields()
+
+    def get_session_fields(self):
+        """Frontend for the same method of the factory's case class"""
+        return self.case_cls.get_session_fields()
+
+    def _build_preset(self, result):
+        return dict((name, result[name])
+                    for name in self.case_cls.get_preset_fields()
+                    if name in result)
+
+    def loadById(self, id):
+        """Load a case with the given id. Return a case object"""
+        # ideally, id should always be an int.  However, sometimes it's
+        # given as a unicode object, so we explicitly convert to int.
+        # FIXME: the callers should be changed so that id is always an int.
+        id = int(id)
+
+        result = None
+        conn, c = None, None
+        try:
+            conn = db.getConnection()
+            c = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
+            fields = self.case_cls.get_preload_fields()
+            query = LOAD_CASE_SQL % dict(fields=", ".join(fields))
+            fields = {'id': id}
+            c.execute(query, fields)
+            result = c.fetchone()
+            if not result:
+                raise LoadCaseNotExistsError("Es konnte keine Fallakte geladen"
+                                             " werden.")
+        finally:
+            db.recycleConnection(conn, c)
+
+        return self.case_cls(id, preset=self._build_preset(result))
+
+    def loadFromQueryResult(self, result):
+        """Create a Case object from a DB query result row.
+
+        The result should be a dict-like object mapping the names used
+        in the formed tree to the values.  Which fields can be used is
+        determined by the list returned by the Case's get_preset_fields
+        method.  In addition to those fields, the row must contain the
+        following fields that will be used to instantiate the State
+        object: s_id, status, zugriff
+        """
+        return self.case_cls(result["id"], preset=self._build_preset(result),
+                             state_id=result["s_id"],
+                             state_status=result["status"],
+                             state_access=result["zugriff"])
+
+    def createNew(self, init=True, uuid=None, data=None):
+        """Create a new case in the database and return the case object.
+        The new case will use the given uuid and contain the data given
+        in the data parameter.  If the init parameter is true the case
+        will get initialized with some standard information like the
+        editor information.
+        """
+        factory = InstanceFactory(g.formedTree, PostgresDBInterface())
+        instance_tree = factory.createNewInstanceTree(uuid)
+        id = instance_tree.getRootNode().getIdentifier()
+
+        if data:
+            self._updateMasterOnCreate(instance_tree, data)
+
+        if init == True:
+            self._initNewCase(id)
+
+        return self.case_cls(id)
+
+    def _updateMasterOnCreate(self, instance_tree, data):
+        id = instance_tree.getRootNode().getIdentifier()
+        try:
+            form_result = convert2dic(data)
+
+            data = {}
+            nkey = None
+            for key, value in form_result.iteritems():
+                nkey = get_field_identifier(id, key, instance_tree)
+                if not nkey:
+                    continue
+                data[nkey] = value
+
+            instance_tree.setData(data)
+
+            session['uncommitted_fields'] = instance_tree.commit()
+            session.save()
+        except SetDataException, err:
+            # FIXME: We should handle this exception in some way.
+            # For now, though, it's better to log it instead of silently
+            # suppressing it.
+            log.exception("SetDataException in _updateMasterOnCreate ignored")
+
+    def _initNewCase(self, id):
+        """Additional initialization of the new case.
+        The base-class method does nothing.  Derived classes should
+        override this method if necessary.
+        """

Modified: wasko/branches/2.0/waskaweb/model/case.py
===================================================================
--- wasko/branches/2.0/waskaweb/model/case.py	2010-02-22 16:06:38 UTC (rev 1677)
+++ wasko/branches/2.0/waskaweb/model/case.py	2010-02-22 16:51:21 UTC (rev 1678)
@@ -39,21 +39,16 @@
 
 from pylons.i18n import _
 
-from formed.instance.backends.postgres import DBFactory as InstanceFactory
-from formed.instance.tree import SetDataException
 from formed.meta import UNKNOWN_DATE
 
 from mpulsweb.lib.base import session, g
-from mpulsweb.lib.db import db, PostgresDBInterface
+from mpulsweb.lib.db import db
 
 from mpulsweb.model.user import UserObject
 from mpulsweb.model.agencysettings import Agency
 from mpulsweb.model.document import listDocuments
-from mpulsweb.model.case import LoadCaseNotExistsError, MpulsCase, \
-     get_field_identifier
+from mpulsweb.model.case import MpulsCase, MpulsCaseFactory
 
-from mpulsweb.controllers.formularpage import convert2dic
-
 from waskaweb.lib.search import CaseSearch
 #from waskaweb.lib.csv import exportAsCSV
 #from waskaweb.lib.excel import exportAsXLS
@@ -97,7 +92,6 @@
     SET phase = %(phase)s
     WHERE id IN (SELECT master_id FROM ka_status_tbl_view WHERE id = %(id)s)"""
 
-LOAD_CASE_SQL = """SELECT %(fields)s FROM master_tbl_view WHERE id = %%(id)s"""
 DELETE_CASE_SQL = """select delete_master_ds(%(id)s)"""
 
 INIT_CASE_SQL = """
@@ -308,115 +302,8 @@
         return self.ds_list
 
 
-class CaseFactory:
+class CaseFactory(MpulsCaseFactory):
 
-    """Factory for case object. This factory provides methods to either load
-    existing cases from db or create new cases"""
-
-    def __init__(self, case_cls=None):
-        if case_cls is None:
-            case_cls = Case
-        self.case_cls = case_cls
-
-    def get_search_retrieve_fields(self):
-        """Frontend for the same method of the factory's case class"""
-        return self.case_cls.get_search_retrieve_fields()
-
-    def get_search_match_fields(self):
-        """Frontend for the same method of the factory's case class"""
-        return self.case_cls.get_search_match_fields()
-
-    def get_session_fields(self):
-        """Frontend for the same method of the factory's case class"""
-        return self.case_cls.get_session_fields()
-
-    def _build_preset(self, result):
-        return dict((name, result[name])
-                    for name in self.case_cls.get_preset_fields()
-                    if name in result)
-
-    def loadById(self, id):
-        """Load a case with the given id. Return a case object"""
-        # ideally, id should always be an int.  However, sometimes it's
-        # given as a unicode object, so we explicitly convert to int.
-        # FIXME: the callers should be changed so that id is always an int.
-        id = int(id)
-
-        result = None
-        conn, c = None, None
-        try:
-            conn = db.getConnection()
-            c = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
-            fields = self.case_cls.get_preload_fields()
-            query = LOAD_CASE_SQL % dict(fields=", ".join(fields))
-            fields = {'id': id}
-            c.execute(query, fields)
-            result = c.fetchone()
-            if not result:
-                raise LoadCaseNotExistsError("Es konnte keine Fallakte geladen"
-                                             " werden.")
-        finally:
-            db.recycleConnection(conn, c)
-
-        return self.case_cls(id, preset=self._build_preset(result))
-
-    def loadFromQueryResult(self, result):
-        """Create a Case object from a DB query result row.
-
-        The result should be a dict-like object mapping the names used
-        in the formed tree to the values.  Which fields can be used is
-        determined by the list returned by the Case's get_preset_fields
-        method.  In addition to those fields, the row must contain the
-        following fields that will be used to instantiate the State
-        object: s_id, status, zugriff
-        """
-        return self.case_cls(result["id"], preset=self._build_preset(result),
-                             state_id=result["s_id"],
-                             state_status=result["status"],
-                             state_access=result["zugriff"])
-
-    def createNew(self, init=True, uuid=None, data=None):
-        """Create a new case in the database and return the case object.
-        The new case will use the given uuid and contain the data given
-        in the data parameter.  If the init parameter is true the case
-        will get initialized with some standard information like the
-        editor information.
-        """
-        factory = InstanceFactory(g.formedTree, PostgresDBInterface())
-        instance_tree = factory.createNewInstanceTree(uuid)
-        id = instance_tree.getRootNode().getIdentifier()
-
-        if data:
-            self._updateMasterOnCreate(instance_tree, data)
-
-        if init == True:
-            self._initNewCase(id)
-
-        return self.case_cls(id)
-
-    def _updateMasterOnCreate(self, instance_tree, data):
-        id = instance_tree.getRootNode().getIdentifier()
-        try:
-            form_result = convert2dic(data)
-
-            data = {}
-            nkey = None
-            for key, value in form_result.iteritems():
-                nkey = get_field_identifier(id, key, instance_tree)
-                if not nkey:
-                    continue
-                data[nkey] = value
-
-            instance_tree.setData(data)
-
-            session['uncommitted_fields'] = instance_tree.commit()
-            session.save()
-        except SetDataException, err:
-            # FIXME: We should handle this exception in some way.
-            # For now, though, it's better to log it instead of silently
-            # suppressing it.
-            log.exception("SetDataException in _updateMasterOnCreate ignored")
-
     def _initNewCase(self, id):
         conn, cur = None, None
         try:



More information about the Mpuls-commits mailing list