[Mpuls-commits] r8 - in trunk: . waskaweb/controllers waskaweb/lib waskaweb/model waskaweb/templates/administration waskaweb/templates/documents

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Wed Aug 13 15:02:49 CEST 2008


Author: thomas
Date: 2008-08-13 15:02:47 +0200 (Wed, 13 Aug 2008)
New Revision: 8

Added:
   trunk/waskaweb/lib/db.py
Removed:
   trunk/waskaweb/lib/db_factory.py
Modified:
   trunk/ChangeLog.txt
   trunk/waskaweb/controllers/administration.py
   trunk/waskaweb/controllers/case.py
   trunk/waskaweb/controllers/document.py
   trunk/waskaweb/controllers/evaluate.py
   trunk/waskaweb/controllers/statement.py
   trunk/waskaweb/controllers/usersettings.py
   trunk/waskaweb/lib/base.py
   trunk/waskaweb/lib/casedata.py
   trunk/waskaweb/lib/evaluation.py
   trunk/waskaweb/lib/helpers.py
   trunk/waskaweb/lib/security.py
   trunk/waskaweb/lib/validators.py
   trunk/waskaweb/model/agency.py
   trunk/waskaweb/model/document.py
   trunk/waskaweb/model/statement.py
   trunk/waskaweb/model/user.py
   trunk/waskaweb/templates/administration/edit_settings.mako
   trunk/waskaweb/templates/administration/show_settings.mako
   trunk/waskaweb/templates/documents/case_overview.mako
   trunk/waskaweb/templates/documents/global_overview.mako
Log:
Load 465f2769604b into trunk.


Modified: trunk/ChangeLog.txt
===================================================================
--- trunk/ChangeLog.txt	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/ChangeLog.txt	2008-08-13 13:02:47 UTC (rev 8)
@@ -1,3 +1,78 @@
+2007-11-28  Sascha L. Teichmann <teichmann at intevation.de>
+
+	* waskaweb/model/document.py: Added a getName() method which
+	  gives the file name in a given encoding. Defaults to UTF-8.
+
+	* waskaweb/templates/documents/case_overview.mako,
+	  waskaweb/templates/documents/global_overview.mako: Use the
+	  new getName() method.
+
+2007-11-28  Sascha L. Teichmann <teichmann at intevation.de>
+
+	* waskaweb/model/agency.py: get() methods return UTF-8 encoded
+	  strings now. This fixes the problem of KA names containing Umlauts.
+
+	* waskaweb/templates/administration/edit_settings.mako,
+	  waskaweb/templates/administration/show_settings.mako: They used
+	  the internal conf dictionary. This is replaced by using the
+	  respective get() methods now.
+
+2007-11-28  Sascha L. Teichmann <teichmann at intevation.de>
+
+	* waskaweb/controllers/case.py: Removed debug output
+
+	* waskaweb/lib/evaluation.py: Fixed wrong spelled connection recycling.
+
+2007-11-28  Sascha L. Teichmann <teichmann at intevation.de>
+
+	* waskaweb/lib/db_factory.py: Removed. Old DB model is no longer
+	  needed.
+
+	* waskaweb/controllers/administration.py,
+	  waskaweb/controllers/case.py,
+	  waskaweb/lib/base.py,
+	  waskaweb/lib/helpers.py,
+	  waskaweb/model/user.py: removed imports of old DB model.
+
+2007-11-27  Sascha L. Teichmann <teichmann at intevation.de>
+
+	* waskaweb/lib/evaluation.py: Correct a few syntax typos.
+
+2007-11-27  Sascha L. Teichmann <teichmann at intevation.de>
+
+	* waskaweb/controllers/administration.py,
+	  waskaweb/controllers/case.py,
+	  waskaweb/controllers/evaluate.py,
+	  waskaweb/controllers/statement.py,
+	  waskaweb/controllers/usersettings.py,
+	  waskaweb/lib/casedata.py,
+	  waskaweb/lib/evaluation.py,
+	  waskaweb/lib/validators.py,
+	  waskaweb/model/statement.py,
+	  waskaweb/model/user.py: Further refactoring to new DB connection
+	  model. Still needs some testing.
+
+2007-11-27  Sascha L. Teichmann <teichmann at intevation.de>
+
+	* waskaweb/lib/db.py: New. Models a thread locale DB connection
+
+	* waskaweb/controllers/case.py,
+	  waskaweb/controllers/document.py,
+	  waskaweb/lib/base.py,
+	  waskaweb/lib/casedata.py,
+	  waskaweb/lib/security.py,
+	  waskaweb/model/agency.py,
+	  waskaweb/model/document.py,
+	  waskaweb/model/statement.py,
+	  waskaweb/model/user.py: Adjusted to use new model. Not
+	  working perfect yet.
+
+2007-11-27  Sascha L. Teichmann <teichmann at intevation.de>
+
+	* waskaweb/lib/base.py: Moved DB connection closing
+	  from __after__ into a try/finally block in __call__.
+	  This fixes issue171. 
+
 2007-11-22  Sascha L. Teichmann <teichmann at intevation.de>
 
 	* waskaweb/controllers/evaluate.py: Use DataApp instead of FileApp

Modified: trunk/waskaweb/controllers/administration.py
===================================================================
--- trunk/waskaweb/controllers/administration.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/controllers/administration.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -2,7 +2,6 @@
 import formencode
 
 from waskaweb.lib.base import *
-from waskaweb.lib.db_factory import *
 from waskaweb.lib.validators import NewUserForm, EditUserForm, NewPasswordForm, EditSettingsForm 
 from waskaweb.model.user import UserObject, UserListObject
 from waskaweb.model.agency import Agency 
@@ -30,23 +29,23 @@
         return render('/administration/account_deactivated.mako')
 
     def overviewUser(self):
-        list = UserListObject(self.db_pool)
+        list = UserListObject()
         c.user_overview = list.getUserList() 
         return render('/administration/overview_user.mako')
 
     def showUser(self, id=None):
-        c.uo = UserObject(self.db_pool, id)
-        c.vuo = UserObject(self.db_pool, c.uo.standin)
+        c.uo = UserObject(id)
+        c.vuo = UserObject(c.uo.standin)
         return render('/administration/show_user.mako')
 
     def editUser(self, id=None):
         c.form_errors = {}
         c.form_result = {}
-        c.uo = UserObject(self.db_pool, id)
+        c.uo = UserObject(id)
         return render('/administration/edit_user.mako') 
 
     def resetUserPassword(self, id=None, confirmed=False):
-        c.uo = UserObject(self.db_pool, id)
+        c.uo = UserObject(id)
         if confirmed:
             try:
                 c.new_password = c.uo.resetPassword()
@@ -68,11 +67,11 @@
         return render('/administration/new_user.mako')
 
     def editUserAction(self):
-        validator = EditUserForm(self.db_pool) 
+        validator = EditUserForm() 
         try:
             try:
                 uid = request.params['uid']
-                c.uo = UserObject(self.db_pool, uid)
+                c.uo = UserObject(uid)
                 form_result = validator.to_python(request.params)
                 c.uo.setData(form_result)
                 c.uo.store()
@@ -86,12 +85,12 @@
             #return "Es ist ein Fehler beim Speichern des Benutzers aufgetreten."
 
     def createUserAction(self):
-        validator = NewUserForm(self.db_pool) 
+        validator = NewUserForm() 
         c.user_password = None
         try:
             try:
                 c.form_result = validator.to_python(request.params)
-                c.uo = UserObject(self.db_pool)
+                c.uo = UserObject()
                 # Set initial data which is needed to create a new user
                 login = c.form_result.get('login', '')
                 role = c.form_result.get('role', '')
@@ -110,7 +109,7 @@
 
     def deleteUser(self, id, confirmed=False):
         try:
-            uo = UserObject(self.db_pool, id)
+            uo = UserObject(id)
             if confirmed:
                 c.notification_for = DELETE_USER_NOTIFICATION 
                 c.notification_text = DELETE_USER_NOTIFICATION_TEXT 
@@ -130,7 +129,7 @@
         c.form_errors = {}
         c.form_result = {}
         try:
-            c.agency = Agency(self.db_pool)
+            c.agency = Agency()
             return render('administration/show_settings.mako')
         except:
             return render('/tests/trace.mako')
@@ -139,7 +138,7 @@
         c.form_errors = {}
         c.form_result = {}
         try:
-            c.agency = Agency(self.db_pool)
+            c.agency = Agency()
             return render('administration/edit_settings.mako')
         except:
             return render('/tests/trace.mako')
@@ -153,16 +152,16 @@
             c.form_errors = error.error_dict or {}
             return render('/administration/edit_settings.mako')
 
-        c.agency = Agency(self.db_pool)
+        c.agency = Agency()
         c.agency.store(c.form_result)
         return self.showSettings()
 
     def viewPrivacyStatement(self):
-        agency = Agency(self.db_pool)
+        agency = Agency()
         statement = agency.getPrivacyStatement() 
         return statement
 
     def viewAidPlanStatement(self):
-        agency = Agency(self.db_pool)
+        agency = Agency()
         statement = agency.getAidPlanStatement() 
         return statement

Modified: trunk/waskaweb/controllers/case.py
===================================================================
--- trunk/waskaweb/controllers/case.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/controllers/case.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -8,7 +8,6 @@
 from waskaweb.lib.base import *
 from waskaweb.lib.evaluation import *
 from waskaweb.lib.casedata import *
-from waskaweb.lib.db_factory import *
 from waskaweb.lib.validators import NewCaseForm, SearchCaseForm, SetStandinForm, SetEditorForm
 from waskaweb.model.user import *
 from waskaweb.model.statement import * 
@@ -64,17 +63,17 @@
         validator = SearchCaseForm()
         try:
             form_result = validator.to_python(request.params)
-            c.cases = DataSetOverviewPage(self.db_pool)
+            c.cases = DataSetOverviewPage()
             c.cases.search(form_result.get('search_str')) 
         except formencode.Invalid, error:
             c.form_result = error.value
             c.form_errors = error.error_dict or {}
-            c.cases = DataSetOverviewPage(self.db_pool)
+            c.cases = DataSetOverviewPage()
             return render('/casemanagement/overview.mako')
         return render('/casemanagement/overview.mako')
 
     def overview(self):
-        c.cases = DataSetOverviewPage(self.db_pool)
+        c.cases = DataSetOverviewPage()
         c.cases.search()
         return render('/casemanagement/overview.mako')
 
@@ -82,14 +81,14 @@
         session['case_modus'] = "show" 
         session['case_id'] = id
         session['case_errors'] = {}
-        c.digest = DataSetDigest(id, self.db_pool) 
+        c.digest = DataSetDigest(id) 
         c.ds_id = id
         session['case_hasStatement'] = c.digest.hasSignedPrivacyStatement() 
         session['case_last_name'] = c.digest.last_name 
         session['case_first_name'] = c.digest.first_name 
         session['case_nr'] = c.digest.knr
         try:
-            k_id = kompetenzId(self.db_pool, int(id))
+            k_id = kompetenzId(int(id))
             #print >> sys.stderr, "Found Kompetenz-Id: %s" % str(k_id)
         except:
             traceback.print_exc(file=sys.stderr)
@@ -120,7 +119,7 @@
             return render('statement/dialogs/missing_statement.mako')
 
     def digest(self, id):
-        c.digest = DataSetDigest(id, self.db_pool) 
+        c.digest = DataSetDigest(id) 
         c.ds_id = id
         session['case_last_name'] = c.digest.last_name 
         session['case_first_name'] = c.digest.first_name 
@@ -165,7 +164,7 @@
         # TODO: Checked routes why 
         #def newAction(self, confirmed=False): Does not work
         if id: # Create emtpy case (no signed statement)
-            dsf = DSFactory(self.db_pool)
+            dsf = DSFactory()
             ds = dsf.createDataset()
             return self.overview()
 
@@ -181,8 +180,8 @@
 
         if request.params.has_key('print'):
             c.print_version = 1
-            statement = PrivacyStatement(self.db_pool)
-            agency = Agency(self.db_pool)
+            statement = PrivacyStatement()
+            agency = Agency()
             dummy = TempDigest(request.params)
             c.content = statement.fillout(dummy, agency) 
             return render('statement/default_statement.mako')
@@ -197,7 +196,7 @@
                 validator = NewCaseForm()
                 try:
                     form_result = validator.to_python(request.params)
-                    dsf = DSFactory(self.db_pool)
+                    dsf = DSFactory()
                     ds = dsf.createDataset()
                     ds.initData()
                     # Prepare params so that _save will eat them an gets all needed
@@ -206,7 +205,7 @@
                     new_params['ds'] = [ds.id]
                     # Does the new case has a signed statement?
                     if request.params.has_key('statement_signed'):
-                        statement = PrivacyStatement(self.db_pool, ds.id)
+                        statement = PrivacyStatement(ds.id)
                         statement.sign()
 
                     self.__save("page_1", new_params, {})
@@ -251,7 +250,7 @@
         # Determine if we have an repeat group or a formular page
         what = ti.page.startswith("rg_") and "rg_aid_overview" or "formular"
         if what == "rg_aid_overview":
-            c.rg_list = DataSetAidList(self.db_pool, ds_id)
+            c.rg_list = DataSetAidList(ds_id)
         else:
             formdata = self._getFormdata(ti, ds_id)
             vr = ViewRenderer(formdata, ro_mode=False)
@@ -280,7 +279,7 @@
         # Determine if we have an repeat group or a formular page
         what = ti.page.startswith("rg_") and "rg_aid_overview" or "formular"
         if what == "rg_aid_overview":
-            c.rg_list = DataSetAidList(self.db_pool, ds_id)
+            c.rg_list = DataSetAidList(ds_id)
         else:
             formdata = self._getFormdata(ti, ds_id)
             vr = ViewRenderer(formdata)
@@ -307,7 +306,7 @@
                 ds_id, 
                 mode="edit",
                 selected_key="14")
-            c.rg_list = DataSetAidList(self.db_pool, ds_id)
+            c.rg_list = DataSetAidList(ds_id)
         else:
             c.form_navigation = self._getFormNavigation(
                 ds_id, 
@@ -338,7 +337,7 @@
                 ds_id, 
                 mode="show",
                 selected_key="14")
-            c.rg_list = DataSetAidList(self.db_pool, ds_id)
+            c.rg_list = DataSetAidList(ds_id)
         else:
             c.form_navigation = self._getFormNavigation(
                 ds_id, 
@@ -379,7 +378,7 @@
         nc = doc.findByClassAndName(PageNode, treeItem.page)
         widgets = nc.allWidgets()
         widgets_names = [w.getName() for w in widgets]
-        page = DataPage(self.db_pool, db_view, widgets_names, ds_id)
+        page = DataPage(db_view, widgets_names, ds_id)
         form_errors = session.get('case_errors', {})
         formdata = FormDataImpl(help=help, page=page, errors=form_errors, nc=[nc])
         return formdata
@@ -430,7 +429,7 @@
                     ti.showPath()
                     c.ds_id   = ti.realId(int(nds))
                     c.page_id = "14"
-                    c.rg_list = DataSetAidList(self.db_pool, nds)
+                    c.rg_list = DataSetAidList(nds)
                     c.form_navigation = self._getFormNavigation(
                         nds,
                         mode="edit",
@@ -461,7 +460,7 @@
             nc = document.findByClassAndName(PageNode, pageName)
             nwidgets = nc.allWidgets()
             widgets_names = [w.getName() for w in nwidgets]
-            dbPage = DataPage(self.db_pool, db_view, widgets_names, ds_id)
+            dbPage = DataPage(db_view, widgets_names, ds_id)
         except:
             print >> sys.stderr, "Could not load datapage"
             return "Could not load datapage"
@@ -577,7 +576,7 @@
             case_id = request.params.getone('case_id')
             page_id = request.params.getone('page_id')
             aid_type = request.params.getone('aid_type')
-            aid = DataSetAidObject(self.db_pool, aid_type)
+            aid = DataSetAidObject(aid_type)
             ds_id = aid.create(int(case_id))
             print >> sys.stderr, "aid:%s, %s, %s" % (aid, ds_id, aid.page_id) 
             if ds_id and aid.page_id:
@@ -589,7 +588,7 @@
 
     def deleteAid(self, ds_id, ds_type, confirmed=False):
         if confirmed == '1':
-            aid = DataSetAidObject(self.db_pool, ds_type, ds_id)
+            aid = DataSetAidObject(ds_type, ds_id)
             if aid.delete():
                 return self.show(session.get('case_id'), '14') # 14 should be the overview page
             # TODO: Create Errorpage
@@ -648,14 +647,14 @@
 
             knummer = self.__fetchKundennummerFromPDF(tbls)
             if not knummer is None:
-                in_db = caseExists(self.db_pool, knummer)
+                in_db = caseExists(knummer)
                 if in_db:
                     c.notification_for  = PDF_DUB_NOTIFICATION 
                     c.notification_text = PDF_DUB_NOTIFICATION_TEXT % knummer
                     c.url_ok = "/case/importCase"
                     return render('/casemanagement/dialogs/notificate_import_dub.mako')
 
-            ds_id = createTables(self.db_pool, tbls)
+            ds_id = createTables(tbls)
             #c.messages = fe.allMessages()
         except:
             c.notification_for  = PDF_DUB_NOTIFICATION 
@@ -690,11 +689,11 @@
             return render('/casemanagement/overview.mako')
 
     def organisation(self, id):
-        list = UserListObject(self.db_pool)
-        c.case = Dataset(self.db_pool, id)
+        list = UserListObject()
+        c.case = Dataset(id)
         c.standin_list = c.case.getStandin()
         c.current_user = session['USER_AUTHORIZED'][2]
-        c.editor = UserObject(self.db_pool, c.case.getEditor())
+        c.editor = UserObject(c.case.getEditor())
         # Get available users for standin. filter out admins and the current
         # user
         filter = [u.id for u in list.getAdminList()]
@@ -710,7 +709,7 @@
         validator = SetEditorForm()
         try:
             form_result = validator.to_python(request.params)
-            case = Dataset(self.db_pool, form_result.get('case_id'))
+            case = Dataset(form_result.get('case_id'))
             case.setEditor(form_result.get('editor'))
             return self.organisation(form_result.get('case_id'))
         except formencode.Invalid, error:
@@ -723,7 +722,7 @@
         data = formencode.variabledecode.variable_decode(request.params)
         try:
             form_result = validator.to_python(data)
-            case = Dataset(self.db_pool, form_result.get('case_id'))
+            case = Dataset(form_result.get('case_id'))
             case.setStandin(form_result.get('standin'))
             return self.organisation(form_result.get('case_id'))
         except formencode.Invalid, error:
@@ -753,7 +752,7 @@
                 id, 
                 mode=session.get('case_modus'))
             id = int(id)
-            c.files = listDocuments(self.db_pool, id)
+            c.files = listDocuments(id)
         except:
             return render('/tests/trace.mako')
         return render('/documents/case_overview.mako')
@@ -768,7 +767,7 @@
     def delete(self, id, confirmed):
         c.ds_id = id
         if confirmed == '1':
-            ds = Dataset(self.db_pool, id)
+            ds = Dataset(id)
             if ds.delete():
                 return self.overview()
             # TODO: Create Errorpage

Modified: trunk/waskaweb/controllers/document.py
===================================================================
--- trunk/waskaweb/controllers/document.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/controllers/document.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -27,7 +27,7 @@
 
     def globalOverview(self):
         try:
-            c.files = listDocuments(self.db_pool)
+            c.files = listDocuments()
         except:
             traceback.print_exc(file=sys.stderr)
             c.files = []
@@ -44,7 +44,7 @@
             try:
                 myfile = request.POST.get('file')
                 if not myfile is None:
-                    doc.create(self.db_pool, myfile.filename, myfile.file)
+                    doc.create(myfile.filename, myfile.file)
             finally:
                 if not myfile is None:
                     try: myfile.file.close()
@@ -67,7 +67,7 @@
             try:
                 myfile = request.POST.get('file')
                 if not myfile is None:
-                    doc.create(self.db_pool, myfile.filename, myfile.file, case)
+                    doc.create(myfile.filename, myfile.file, case)
             finally:
                 if not myfile is None:
                     try: myfile.file.close()
@@ -86,7 +86,7 @@
 
         try:
             document = Document(id)
-            document.load(self.db_pool)
+            document.load()
             data = paste.fileapp.DataApp(
                 document.data,
                 content_type=document.mime)
@@ -104,7 +104,7 @@
 
         try:
             document = Document(id)
-            document.load(self.db_pool, True)
+            document.load(True)
             data = paste.fileapp.DataApp(
                 document.data,
                 content_type=document.mime)
@@ -122,7 +122,7 @@
 
         if confirmed:
             try:
-                deleteDocument(self.db_pool, id)
+                deleteDocument(id)
             except:
                 traceback.print_exc(file=sys.stderr)
                 return self.globalOverview()
@@ -146,7 +146,7 @@
 
         if confirmed:
             try:
-                deleteDocument(self.db_pool, id, True)
+                deleteDocument(id, True)
             except:
                 traceback.print_exc(file=sys.stderr)
                 #return render('/tests/trace.mako') 

Modified: trunk/waskaweb/controllers/evaluate.py
===================================================================
--- trunk/waskaweb/controllers/evaluate.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/controllers/evaluate.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -3,7 +3,6 @@
 
 from waskaweb.lib.base import *
 from waskaweb.lib.evaluation import *
-from waskaweb.lib.db_factory import *
 
 log = logging.getLogger(__name__)
 
@@ -16,56 +15,39 @@
         # Return a rendered template
         #   return render('/some/template.mako')
         # or, Return a response
-        return "404"
+        raise paste.httpexceptions.HTTPException(404)
         
     def evaluate(self):
         try:
-            try:
-                conn = self.db_pool.getConnection()
-                e1 = Evaluation_1(conn)
-                c.eval_1_total, c.eval_1_cm, c.eval_1_percent = e1.perform()
+            e1 = Evaluation_1()
+            c.eval_1_total, c.eval_1_cm, c.eval_1_percent = e1.perform()
 
-                conn = self.db_pool.getConnection()
-                e2 = Evaluation_2(conn)
-                c.eval_2_t, c.eval_2_m, c.eval_2_w, c.eval_2_i = e2.perform()
+            e2 = Evaluation_2()
+            c.eval_2_t, c.eval_2_m, c.eval_2_w, c.eval_2_i = e2.perform()
 
-                conn = self.db_pool.getConnection()
-                e3 = Evaluation_3(conn)
-                c.eval_3 = e3.perform()
+            e3 = Evaluation_3()
+            c.eval_3 = e3.perform()
 
-                conn = self.db_pool.getConnection()
-                e4 = Evaluation_4(conn)
-                c.eval_4 = e4.perform()
+            e4 = Evaluation_4()
+            c.eval_4 = e4.perform()
 
-                conn = self.db_pool.getConnection()
-                e5 = Evaluation_5(conn)
-                c.eval_5 = e5.perform()
+            e5 = Evaluation_5()
+            c.eval_5 = e5.perform()
 
-                conn = self.db_pool.getConnection()
-                e6 = Evaluation_6(conn)
-                c.eval_6 = e6.perform()
+            e6 = Evaluation_6()
+            c.eval_6 = e6.perform()
 
-                conn = self.db_pool.getConnection()
-                e7 = Evaluation_7(conn)
-                c.eval_7 = e7.perform()
+            e7 = Evaluation_7()
+            c.eval_7 = e7.perform()
 
-                conn = self.db_pool.getConnection()
-                e8 = Evaluation_8(conn) 
-                c.eval_8 = e8.perform()
+            e8 = Evaluation_8() 
+            c.eval_8 = e8.perform()
 
-                conn = self.db_pool.getConnection()
-                e9 = Evaluation_9(conn)
-                c.eval_9 = e9.perform()
+            e9 = Evaluation_9()
+            c.eval_9 = e9.perform()
 
-                conn = self.db_pool.getConnection()
-                e10 = Evaluation_10(conn)
-                c.eval_10 = e10.perform()
-            finally:
-                try:
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+            e10 = Evaluation_10()
+            c.eval_10 = e10.perform()
         except:
             return render('/tests/trace.mako')
         return render('casemanagement/evaluation_result.mako')
@@ -80,151 +62,80 @@
         
     def exportEvaluation_1(self):
         try:
-            try:
-                conn = self.db_pool.getConnection()
-                e = Evaluation_1(conn)
-                return self._export(e)
-            finally:
-                try:
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+            e = Evaluation_1()
+            return self._export(e)
         except:
             traceback.print_exc(file=sys.stderr)
             raise paste.httpexceptions.HTTPException(404)
 
     def exportEvaluation_2(self):
         try:
-            try:
-                conn = self.db_pool.getConnection()
-                e = Evaluation_2(conn)
-                return self._export(e)
-            finally:
-                try:
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+            e = Evaluation_2()
+            return self._export(e)
         except:
-            pass
+            traceback.print_exc(file=sys.stderr)
+            raise paste.httpexceptions.HTTPException(404)
 
     def exportEvaluation_3(self):
         try:
-            try:
-                conn = self.db_pool.getConnection()
-                e = Evaluation_3(conn)
-                return self._export(e)
-            finally:
-                try:
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+            e = Evaluation_3()
+            return self._export(e)
         except:
-            pass
+            traceback.print_exc(file=sys.stderr)
+            raise paste.httpexceptions.HTTPException(404)
 
     def exportEvaluation_4(self):
         try:
-            try:
-                conn = self.db_pool.getConnection()
-                e = Evaluation_4(conn)
-                return self._export(e)
-            finally:
-                try:
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+            e = Evaluation_4()
+            return self._export(e)
         except:
-            pass
+            traceback.print_exc(file=sys.stderr)
+            raise paste.httpexceptions.HTTPException(404)
 
     def exportEvaluation_5(self):
         try:
-            try:
-                conn = self.db_pool.getConnection()
-                e = Evaluation_5(conn)
-                return self._export(e)
-            finally:
-                try:
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+            e = Evaluation_5()
+            return self._export(e)
         except:
-            pass
+            traceback.print_exc(file=sys.stderr)
+            raise paste.httpexceptions.HTTPException(404)
 
     def exportEvaluation_6(self):
         try:
-            try:
-                conn = self.db_pool.getConnection()
-                e = Evaluation_6(conn)
-                return self._export(e)
-            finally:
-                try:
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+            e = Evaluation_6()
+            return self._export(e)
         except:
-            pass
+            traceback.print_exc(file=sys.stderr)
+            raise paste.httpexceptions.HTTPException(404)
 
     def exportEvaluation_7(self):
         try:
-            try:
-                conn = self.db_pool.getConnection()
-                e = Evaluation_7(conn)
-                return self._export(e)
-            finally:
-                try:
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+            e = Evaluation_7()
+            return self._export(e)
         except:
-            pass
+            traceback.print_exc(file=sys.stderr)
+            raise paste.httpexceptions.HTTPException(404)
 
     def exportEvaluation_8(self):
         try:
-            try:
-                conn = self.db_pool.getConnection()
-                e = Evaluation_8(conn)
-                return self._export(e)
-            finally:
-                try:
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+            e = Evaluation_8()
+            return self._export(e)
         except:
-            pass
+            traceback.print_exc(file=sys.stderr)
+            raise paste.httpexceptions.HTTPException(404)
 
     def exportEvaluation_9(self):
         try:
-            try:
-                conn = self.db_pool.getConnection()
-                e = Evaluation_9(conn)
-                return self._export(e)
-            finally:
-                try:
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+            e = Evaluation_9()
+            return self._export(e)
         except:
-            pass
+            traceback.print_exc(file=sys.stderr)
+            raise paste.httpexceptions.HTTPException(404)
 
     def exportEvaluation_10(self):
         try:
-            try:
-                conn = self.db_pool.getConnection()
-                e = Evaluation_10(conn)
-                return self._export(e)
-            finally:
-                try:
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+            e = Evaluation_10()
+            return self._export(e)
         except:
-            pass
+            traceback.print_exc(file=sys.stderr)
+            raise paste.httpexceptions.HTTPException(404)

Modified: trunk/waskaweb/controllers/statement.py
===================================================================
--- trunk/waskaweb/controllers/statement.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/controllers/statement.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -24,22 +24,24 @@
         redirect_to(controller="waska", action="start")
 
     def printAidPlanStatement(self, id):
-        digest = DataSetDigest(id, self.db_pool)
-        statement = AidPlanStatement(self.db_pool, id)
-        agency = Agency(self.db_pool)
-        rg_list = DataSetAidList(self.db_pool, id)
-        c.content = statement.fillout(digest, agency, rg_list=rg_list.getDatasets()) 
+        digest = DataSetDigest(id)
+        statement = AidPlanStatement(id)
+        agency = Agency()
+        rg_list = DataSetAidList(id)
+        c.content = statement.fillout(
+            digest, agency, rg_list=rg_list.getDatasets()) 
         return render('statement/default_statement.mako')
 
     def printPrivacyStatement(self, id):
-        digest = DataSetDigest(id, self.db_pool)
-        statement = PrivacyStatement(self.db_pool, id)
-        agency = Agency(self.db_pool)
+        digest = DataSetDigest(id)
+        statement = PrivacyStatement(id)
+        agency = Agency()
         c.content = statement.fillout(digest, agency) 
         return render('statement/default_statement.mako')
 
     def setPrivacyStatement(self, id):
-        c.form_navigation = self._getFormNavigation(id, session.get("case_modus", "show"))
+        c.form_navigation = self._getFormNavigation(
+            id, session.get("case_modus", "show"))
         c.ds_id = id
         return render('statement/edit.mako')
 
@@ -50,9 +52,10 @@
             return self.declinePrivacyStatement(request.params['case_id'], '0')
 
     def acceptPrivacyStatement(self, id, confirmed):
-        c.form_navigation = self._getFormNavigation(id, session.get("case_modus", "show"))
+        c.form_navigation = self._getFormNavigation(
+            id, session.get("case_modus", "show"))
         if confirmed == '1':
-            statement = PrivacyStatement(self.db_pool, id)
+            statement = PrivacyStatement(id)
             statement.sign()
             session['case_hasStatement'] = True
             session.save()
@@ -60,14 +63,17 @@
         else:
             c.confirm_for = HEADER 
             c.question = ACCEPT_QUESTION 
-            c.url_yes = h.url_for(controller="statement", action="acceptPrivacyStatement", id=id, confirmed="1")
+            c.url_yes = h.url_for(
+                controller="statement", 
+                action="acceptPrivacyStatement", id=id, confirmed="1")
             c.url_no = h.url_for('digest', id=id)
             return render('statement/dialogs/confirm.mako')
 
     def declinePrivacyStatement(self, id, confirmed):
-        c.form_navigation = self._getFormNavigation(id, session.get("case_modus", "show"))
+        c.form_navigation = self._getFormNavigation(
+            id, session.get("case_modus", "show"))
         if confirmed == '1':
-            statement = PrivacyStatement(self.db_pool, id)
+            statement = PrivacyStatement(id)
             statement.decline()
             # TODO: Delete case or delete personal data from case, at least hide
             # this case in the case list from further editing by the user.
@@ -79,7 +85,9 @@
         else:
             c.confirm_for = HEADER 
             c.question = DECLINE_QUESTION 
-            c.url_yes = h.url_for(controller="statement", action="declinePrivacyStatement", id=id, confirmed="1")
+            c.url_yes = h.url_for(
+                controller="statement", 
+                action="declinePrivacyStatement", id=id, confirmed="1")
             c.url_no = h.url_for('digest', id=id)
             return render('statement/dialogs/confirm.mako')
        
@@ -87,6 +95,8 @@
         # Set errors for navigation
         errors = session.get('case_errors', {})
         navigation = session.get('navigation.tree')
-        return navigation.render(lambda t: '/case/%sToggle/%s/%s' % (mode, session.get('case_id'), t.key))
+        return navigation.render(
+            lambda t: '/case/%sToggle/%s/%s' % (
+                mode, session.get('case_id'), t.key))
 
 # vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8:

Modified: trunk/waskaweb/controllers/usersettings.py
===================================================================
--- trunk/waskaweb/controllers/usersettings.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/controllers/usersettings.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -19,8 +19,8 @@
         return 'Hello World'
 
     def showSettings(self, id):
-        c.uo = UserObject(self.db_pool, id)
-        c.vuo = UserObject(self.db_pool, c.uo.standin)
+        c.uo = UserObject(id)
+        c.vuo = UserObject(c.uo.standin)
         return render('/usersettings/show_settings.mako') 
 
     def changePassword(self):
@@ -33,7 +33,7 @@
         try:
             try:
                 uid = request.params['uid']
-                c.uo = UserObject(self.db_pool, uid)
+                c.uo = UserObject(uid)
                 form_result = validator.to_python(request.params)
                 new_pass = c.uo.setPassword(form_result.get('passwd'))
                 if new_pass:
@@ -67,13 +67,9 @@
             try:
                 form_result = validator.to_python(request.params)
                 login, password, user = session['USER_AUTHORIZED']
-                user.db_pool = self.db_pool
                 new_pass = user.setPassword(form_result.get('passwd'))
                 if new_pass:
                     # Save new password in the session
-                    # Seting db_pool to None as it could not be pickled in the
-                    # session
-                    user.db_pool = None
                     session['USER_AUTHORIZED'] = (login, new_pass, user)
                     session.save()
                     c.notification_for = SET_PASSWORD_NOTIFICATION_HEADER
@@ -92,8 +88,8 @@
     def editStandin(self, id):
         c.form_errors = {}
         c.form_result = {}
-        ulo = UserListObject(self.db_pool)
-        c.uo = UserObject(self.db_pool, id) 
+        ulo = UserListObject()
+        c.uo = UserObject(id) 
         user = session['USER_AUTHORIZED'][2]
         # Get available users for standin. filter out admins and the current
         # user
@@ -106,7 +102,7 @@
         validator = BaseFormValidator()
         try:
             c.form_result = validator.to_python(request.params)
-            c.uo = UserObject(self.db_pool, c.form_result.get('uid'))
+            c.uo = UserObject(c.form_result.get('uid'))
             c.uo.setStandin(c.form_result.get('standin') or None)
             #TODO: Update the value for the logged in session user
         except formencode.Invalid, error:

Modified: trunk/waskaweb/lib/base.py
===================================================================
--- trunk/waskaweb/lib/base.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/lib/base.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -12,8 +12,9 @@
 
 import waskaweb.lib.helpers as h
 import waskaweb.model as model
-from waskaweb.lib.db_factory import *
 
+import waskaweb.lib.db as db
+
 from waskaweb.lib.security import HOST, PORT, DBNAME, USER, getDbName
 
 import sys
@@ -37,45 +38,55 @@
 
 class BaseController(WSGIController):
     def __init__(self):
-        self.db_pool = None
+        self.db = None
 
     def __before__(self):
-        # Check if the user is already authorized. If not then redirect the user
-        # to the login page
+        # Check if the user is already authorized. 
+        # If not then redirect the user to the login page
         try:
             login, passwd, user = session['USER_AUTHORIZED']
             dbname = getDbName() 
-            #conn_url = CONN_URL % (dbname, dbname, login, passwd)
-            self.db_pool = DBPool(
+
+            self.db = db.DB(
                 dbname   = DBNAME % dbname,
                 host     = HOST,
                 port     = PORT,
                 user     = USER % (dbname, login),
                 password = passwd)
 
+            db.enter(self.db)
+
             # Is the user activated?
-            if not user.isActivated() and not request.path_info in ('/administration/accountDeactivated', '/styles/web.css', '/styles/all.css'):
-                print request.path_info
+            if not user.isActivated() \
+            and not request.path_info in ('/administration/accountDeactivated', '/styles/web.css', '/styles/all.css'):
+                #print request.path_info
                 redirect_to(controller="administration", action="accountDeactivated")
+
             # Do the user needs to change his passwort?
-            if user.needsNewPass() and not request.path_info in ('/usersettings/changePasswordOnLogin', '/usersettings/changePasswordOnLoginAction', '/styles/web.css', '/styles/all.css'):
+            if user.needsNewPass() \
+            and not request.path_info in ('/usersettings/changePasswordOnLogin', '/usersettings/changePasswordOnLoginAction', '/styles/web.css', '/styles/all.css'):
                 redirect_to(controller="usersettings", action="changePasswordOnLogin")
+
         except KeyError:
             p = str(request.path_info)
             if not p in ( '/waska/login', '/waska/loginAction'):# and not inPositive(p):
                 print >> sys.stderr, "Redirect to: '%s' %s" % (request.path_info, str(inPositive(p)))
                 redirect_to(h.url_for(controller='/waska', action='login'))
 
-    def __after__(self):
-        if self.db_pool:
-            self.db_pool.closeConnection()
-
     def __call__(self, environ, start_response):
         """Invoke the Controller"""
         # WSGIController.__call__ dispatches to the Controller method
         # the request is routed to. This routing information is
         # available in environ['pylons.routes_dict']
-        return WSGIController.__call__(self, environ, start_response)
+        try:
+            return WSGIController.__call__(self, environ, start_response)
+        finally:
+            _db = self.db
+            if _db:
+                self.db = None
+                db.leave(_db)
+                _db.closeConnections()
+            
 
 # Include the '_' function in the public names
 __all__ = [__name for __name in locals().keys() if not __name.startswith('_') \

Modified: trunk/waskaweb/lib/casedata.py
===================================================================
--- trunk/waskaweb/lib/casedata.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/lib/casedata.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -15,6 +15,8 @@
 from waskaweb.model.agency import Agency
 from waskaweb.lib.base import session 
 
+from waskaweb.lib.db import db
+
 #sql statements used by the DSFactory
 GET_ALL_DS_SQL = """SELECT id FROM master_tbl_view ORDER by name_1"""
 SEARCH_DS_SQL = """SELECT id FROM master_tbl_view WHERE
@@ -95,8 +97,7 @@
     return isinstance(x, str) and unicode(x, 'utf-8') or x
 
 class DataPage(Page):
-    def __init__(self, dbFactory, relation, items, id):
-        self.dbFactory = dbFactory
+    def __init__(self, relation, items, id):
         self.items     = items # TODO: check for SQL injection
         self.data      = None
         self.relation  = relation # TODO: check for SQL injection
@@ -149,21 +150,15 @@
             self.relation, ", ".join(keys))
 
         try:
-            con = None
-            cur = None
+            con, cur = None, None
             try:
-                con = self.dbFactory.getConnection()
+                con = db.getConnection()
                 cur = con.cursor()
                 #cur.execute(stmnt)
                 cur.execute(stmnt, fields)
                 con.commit()
             finally:
-                if cur:
-                    try: cur.close()
-                    except: pass
-                if con:
-                    try: self.dbFactory.recycleConnection(con)
-                    except: pass
+                db.recycleConnection(con, cur)
 
             # mark as written
             for v in data.itervalues():
@@ -180,31 +175,23 @@
             pass
         stmnt = "SELECT %s FROM %s WHERE id = %%(id)s;" % (fields, self.relation)
         try:
-            con = None
-            cur = None
+            con, cur = None, None
             try:
-                con = self.dbFactory.getConnection()
+                con = db.getConnection()
                 cur = con.cursor()
                 cur.execute(stmnt, { 'id': int(self.id)})
                 res = cur.fetchone()
             finally:
-                if cur:
-                    try: cur.close()
-                    except: pass
-                if con:
-                    try: self.dbFactory.recycleConnection(con)
-                    except: pass
+                db.recycleConnection(con, cur)
             if res:
                 self.data = dict(
                     zip(self.items, [[convert(item), False] for item in res]))
-                #print str(self.data)
 
         except dbapi.Error, err:
             print >> sys.stderr, "DB error: %s" % str(err)
 
 class DataSetAidObject:
-    def __init__(self, db_pool=None, aid_type=None, id=None, sql=None):
-        self.db_pool = db_pool
+    def __init__(self, aid_type=None, id=None, sql=None):
         self.id = id 
         self.start_date = "-/-" 
         self.end_date = "-/-" 
@@ -226,11 +213,10 @@
             self._fetchData(id, sql)
 
     def _fetchData(self, id, sql):
-        conn = None
-        cur = None
+        conn, cur = None, None
         try:
             try:
-                conn = self.db_pool.getConnection()
+                conn = db.getConnection()
                 cur = conn.cursor()
                 sql = sql % id
                 cur.execute(sql)
@@ -244,22 +230,15 @@
                 self.start_date = r[4].strftime('%d.%m.%Y')
                 self.end_date = r[5].strftime('%d.%m.%Y')
             finally:
-                try:
-                    if cur:
-                        cur.close()
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+                db.recycleConnection(conn, cur)
         except:
             pass
 
     def create(self, case_id):
-        conn = None
-        cur = None
         try:
+            conn, cur = None, None
             try:
-                conn = self.db_pool.getConnection()
+                conn = db.getConnection()
                 cur = conn.cursor()
                 sql = AID[str(self.type_id)][2]
                 cur.execute(sql, { 'id': case_id })
@@ -268,91 +247,73 @@
                 # Set data
                 self.id = r[0]
             finally:
-                try:
-                    if cur:
-                        cur.close()
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
-        except StandardError, err:
-            pass
+                db.recycleConnection(conn, cur)
+        except:
+            traceback.print_exc(file=sys.stderr)
+
         return self.id
 
     def delete(self):
-        conn = None
-        cur = None
-        sql = None
+        conn, cur, sql = None, None, None
         try:
             try:
-                conn = self.db_pool.getConnection()
+                conn = db.getConnection()
                 cur = conn.cursor()
                 sql = (AID[str(self.type_id)][4]) # get delete function
                 cur.execute(sql, { 'id': self.id })
                 conn.commit()
             finally:
-                try:
-                    if cur:
-                        cur.close()
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    print >> sys.stderr, "Could not recycle connection"
+                db.recycleConnection(conn, cur)
         except StandardError, err:
             print >> sys.stderr, "Error on deleting aid object", str(err), " ", sql 
         return True
 
 class DataSetAidList:
-    def __init__(self, db_pool, case_id):
+    def __init__(self, case_id):
         self.aid_list = []
-        self.db_pool = db_pool
-        conn = None
-        c = None
+        conn, c = None, None
         try:
             try:
-                conn = self.db_pool.getConnection()
+                conn = db.getConnection()
                 # Bildenden Bereich 
                 c = conn.cursor()
                 sql = FETCH_AID_LIST_SQL % (AID_0_DB_TBL, case_id)
                 #print >> sys.stderr, str(sql)
                 c.execute(sql)
                 for r in c.fetchall():
-                    self.aid_list.append(DataSetAidObject(self.db_pool, 0, r[0], FETCH_AID_0_SQL))
-                c.close()
+                    self.aid_list.append(
+                        DataSetAidObject(0, r[0], FETCH_AID_0_SQL))
+                c.close(); c = None
                 # Berufsvorbereitung
                 c = conn.cursor()
                 sql = FETCH_AID_LIST_SQL % (AID_1_DB_TBL, case_id)
                 #print >> sys.stderr, str(sql)
                 c.execute(sql)
                 for r in c.fetchall():
-                    self.aid_list.append(DataSetAidObject(self.db_pool, 1, r[0], FETCH_AID_1_SQL))
-                c.close()
+                    self.aid_list.append(DataSetAidObject(
+                        1, r[0], FETCH_AID_1_SQL))
+                c.close(); c = None
                 # Berufliche Qualifizierung
                 c = conn.cursor()
                 sql = FETCH_AID_LIST_SQL % (AID_2_DB_TBL, case_id)
                 #print >> sys.stderr, str(sql)
                 c.execute(sql)
                 for r in c.fetchall():
-                    self.aid_list.append(DataSetAidObject(self.db_pool, 2, r[0], FETCH_AID_2_SQL))
-                c.close()
+                    self.aid_list.append(
+                        DataSetAidObject(2, r[0], FETCH_AID_2_SQL))
+                c.close(); c = None
                 # Bildenden Bereich 
                 c = conn.cursor()
                 sql = FETCH_AID_LIST_SQL % (AID_3_DB_TBL, case_id)
                 #print >> sys.stderr, str(sql)
                 c.execute(sql)
                 for r in c.fetchall():
-                    self.aid_list.append(DataSetAidObject(self.db_pool, 3, r[0], FETCH_AID_3_SQL))
+                    self.aid_list.append(DataSetAidObject(
+                        3, r[0], FETCH_AID_3_SQL))
             finally:
-                try:
-                    if c:
-                        c.close()
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+                db.recycleConnection(conn, c)
         except StandardError, err:
             print >> sys.stderr, "%s" % str(err)
-            pass
 
     def numDatasets(self):
         return len(self.aid_list) 
@@ -365,15 +326,14 @@
 
 class DataSetOverviewPage:
 
-    def __init__(self, db_pool, search_str=None):
-        self.db_pool = db_pool
+    def __init__(self, search_str=None):
         self.ds_list = []
 
     def search(self, search_str=None):
         self.ds_list = []
-        f = DSFactory(self.db_pool)
+        f = DSFactory()
         for id in f.listDatasetIds(search_str):
-            self.ds_list.append(DataSetOverviewObject(id, self.db_pool))
+            self.ds_list.append(DataSetOverviewObject(id))
 
     def numDatasets(self):
         return len(self.ds_list) 
@@ -385,34 +345,32 @@
         return [ds.id for ds in self.ds_list]
 
 class DataSetOverviewObject:
-    def __init__(self, id, db_pool):
+    def __init__(self, id):
         self.id = id
         self.first_name = None
         self.last_name = None
         self.knr = None
-        self.db_pool = db_pool
         self._loadFromDB(id)
 
     def _loadFromDB(self, id):
-        # XXX: Not ensured that conn is given back to pool!
-        conn = self.db_pool.getConnection()
-        c = conn.cursor()
-        # XXX: Use prepared statement here
-        sql = """SELECT name_1, vorname_1, kundennummer from master_tbl_view WHERE id = %s""" % str(id)
-        result = None
-        try:
-            c.execute(sql)
-            result = c.fetchone()
-            c.close()
-            self.db_pool.recycleConnection(conn)
-        except StandardError, err:
-            print "DataSetOverviewObject: %s " % str(err)
         try:        
-            self.last_name = unicode(str(result[0]), 'utf-8')
+            conn, c = None, None
+            try:
+                conn = db.getConnection()
+                c = conn.cursor()
+                # XXX: Use prepared statement here
+                sql = """SELECT name_1, vorname_1, kundennummer from master_tbl_view WHERE id = %s""" % str(id)
+                result = None
+                c.execute(sql)
+                result = c.fetchone()
+            finally:
+                db.recycleConnection(conn, c)
+
+            self.last_name  = unicode(str(result[0]), 'utf-8')
             self.first_name = unicode(str(result[1]), 'utf-8')
-            self.knr = unicode(str(result[2]), 'utf-8')
+            self.knr        = unicode(str(result[2]), 'utf-8')
         except:
-            pass
+            traceback.print_exc(file=sys.stderr)
 
 class TempDigest:
     def __init__(self, params):
@@ -423,7 +381,7 @@
         self.city = params.get('wohnort') or '-/-'
 
 class DataSetDigest:
-    def __init__(self, id, db_pool):
+    def __init__(self, id):
         self.id = id
         self.first_name = '' 
         self.last_name = '' 
@@ -435,79 +393,67 @@
         self.telephone = ''
         self.statement = '' 
 
-        self.db_pool = db_pool
         self._loadFromDB(id)
 
     def hasSignedPrivacyStatement(self):
         return self.statement
 
     def _loadFromDB(self, id):
-        conn = self.db_pool.getConnection()
-        c = conn.cursor()
-        sql = """SELECT name_1, 
-                    vorname_1, 
-                    kundennummer,
-                    date_part('year', age(geburtsdatum::timestamp)) as alter,
-                    plz,
-                    strasse,
-                    wohnort,
-                    vorwahl,
-                    telefon_1,
-                    einverstaendniserklaerung
-                    from master_tbl_view WHERE id = %s""" % str(id)
-        result = None
         try:
-            c.execute(sql)
-            result = c.fetchone()
-            c.close()
-            self.db_pool.recycleConnection(conn)
-        except StandardError, err:
-            print "DataSetOverviewObject: %s " % str(err)
-        try: 
-            self.last_name = unicode(str(result[0]), 'utf-8')
+            # XXX: Use prepared statements here
+            sql = """SELECT name_1, 
+                        vorname_1, 
+                        kundennummer,
+                        date_part('year', age(geburtsdatum::timestamp)) as alter,
+                        plz,
+                        strasse,
+                        wohnort,
+                        vorwahl,
+                        telefon_1,
+                        einverstaendniserklaerung
+                        from master_tbl_view WHERE id = %s""" % str(id)
+            result = None
+            conn, c = None, None
+            try:
+                conn = db.getConnection()
+                c    = conn.cursor()
+                c.execute(sql)
+                result = c.fetchone()
+            finally:
+                db.recycleConnection(conn, c)
+            self.last_name  = unicode(str(result[0]), 'utf-8')
             self.first_name = unicode(str(result[1]), 'utf-8')
-            self.knr = unicode(str(result[2]), 'utf-8')
-            if result[3]:
-                self.age =  "%.0f" % result[3]
-            else: 
-                self.age = ""
-            self.plz = unicode(str(result[4]), 'utf-8')
-            self.address = unicode(str(result[5]), 'utf-8')
-            self.city = unicode(str(result[6]), 'utf-8')
+            self.knr        = unicode(str(result[2]), 'utf-8')
+            if result[3]: self.age = "%.0f" % result[3]
+            else:         self.age = ""
+            self.plz         = unicode(str(result[4]), 'utf-8')
+            self.address     = unicode(str(result[5]), 'utf-8')
+            self.city        = unicode(str(result[6]), 'utf-8')
             self.telephone_1 = u"%s" % unicode(str(result[7]), 'utf-8')
             self.telephone_2 = u"%s" % unicode(str(result[8]), 'utf-8')
             self.statement = (result[9] >= 0)
-        except StandardError, err:
-            print >> sys.stderr, "Error! Could not read out case digest: %s" % str(err)
-            pass
+        except:
+            traceback.print_exc(file=sys.stderr)
 
 class DatasetStandin:
-    def __init__(self, db_pool=None, case_id=None):
-        self.db_pool = db_pool
+    def __init__(self, case_id=None):
         self.case_id = case_id
         self.user_ids = []
         self._loadFromDB()
 
     def _loadFromDB(self):
-        con = None
-        cur = None
         sql = LOAD_STANDIN_SQL
         fields = {'id': self.case_id}
+        con, cur = None, None
         try:
-            con = self.db_pool.getConnection()
+            con = db.getConnection()
             cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
             cur.execute(LOAD_STANDIN_SQL, fields)
             rows = cur.fetchall()
             for row in rows:
                 self.user_ids.append(row['benutzer_id'])
         finally:
-            try:
-                if cur:
-                    cursor.close()
-                if con:
-                    self.db_pool.recycleConnection(con)
-            except:
-                pass
+            db.recycleConnection(con, cur)
 
     def getStandin(self):
         return self.user_ids
@@ -519,11 +465,10 @@
         self._add(new - old)
 
     def _delete(self, userid_list):
-        con = None
-        cur = None
+        con, cur = None, None
         fields = {'caseid': self.case_id, 'userid': None}
         try:
-            con = self.db_pool.getConnection()
+            con = db.getConnection()
             for uid in userid_list:
                 fields['userid'] = uid
                 cur = con.cursor()
@@ -531,23 +476,16 @@
                     cur.execute(DELETE_STANDIN_SQL, fields)
                 except:
                     con.rollback()
-                cur.close()
+                cur.close(); cur = None
             con.commit()
         finally:
-            try:
-                if cur:
-                    cursor.close()
-                if con:
-                    self.db_pool.recycleConnection(con)
-            except:
-                pass
+            db.recycleConnection(con, cur)
 
     def _add(self, userid_list):
-        con = None
-        cur = None
+        con, cur = None, None
         fields = {'caseid': self.case_id, 'userid': None}
         try:
-            con = self.db_pool.getConnection()
+            con = db.getConnection()
             for uid in userid_list:
                 fields['userid'] = uid
                 cur = con.cursor()
@@ -555,56 +493,41 @@
                     cur.execute(ADD_STANDIN_SQL, fields)
                 except:
                     con.rollback()
-                cur.close()
+                cur.close(); cur = None
             con.commit()
         finally:
-            try:
-                if cur:
-                    cursor.close()
-                if con:
-                    self.db_pool.recycleConnection(con)
-            except:
-                pass
+            db.recycleConnection(con, cur)
 
 class Dataset(Id):
-    def __init__(self, db_pool=None, id=None, key=None, parent=None):
+    def __init__(self, id=None, key=None, parent=None):
         Id.__init__(self, id, key, parent)
-        self.db_pool = db_pool 
         self.id = id 
         self.editor = None
         if id:
-            self.standin = DatasetStandin(self.db_pool, id) 
+            self.standin = DatasetStandin(id) 
             self._loadFromDB()
 
     def _loadFromDB(self):
-        con = None
-        cur = None
+        con, cur = None, None
         sql = LOAD_DS_SQL
         fields = {'id': self.id}
         try:
-            con = self.db_pool.getConnection()
+            con = db.getConnection()
             cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
             cur.execute(LOAD_DS_SQL, fields)
             row = cur.fetchone()
             self.editor = row['bearbeiter_id']
         finally:
-            try:
-                if cur:
-                    cursor.close()
-                if con:
-                    self.db_pool.recycleConnection(con)
-            except:
-                pass
+            db.recycleConnection(con, cur)
 
     def getEditor(self):
         return self.editor
 
     def setEditor(self, userid):
-        con = None
-        cur = None
+        con, curr = None, None
         fields = {'caseid': self.id, 'userid': userid}
         try:
-            con = self.db_pool.getConnection()
+            con = db.getConnection()
             cur = con.cursor()
             try:
                 cur.execute(SET_EDITOR_SQL, fields)
@@ -612,14 +535,7 @@
                 con.rollback()
             con.commit()
         finally:
-            try:
-                if cur:
-                    cursor.close()
-                if con:
-                    self.db_pool.recycleConnection(con)
-            except:
-                pass
-        
+            db.recycleConnection(con, cur)
 
     def getStandin(self):
         return self.standin.getStandin()
@@ -634,23 +550,16 @@
         return None
 
     def create(self):
-        conn = None
-        cur = None
+        conn, cur = None, None
         try:
             try:
-                conn = self.db_pool.getConnection()
-                cur = conn.cursor()
+                conn = db.getConnection()
+                cur  = conn.cursor()
                 cur.execute(CREATE_DS_SQL)
                 self.id = cur.fetchone()[0]
                 conn.commit()
             finally:
-                try:
-                    if cur:
-                        cur.close()
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+                db.recycleConnection(conn, cur)
             # XXX: This a workaround the RGs
             self.createDependencies()
         except:
@@ -659,37 +568,28 @@
         return self.id 
 
     def initData(self):
-        conn = None
-        cur = None
+        conn, cur = None, None
         try:
             login, passwd, user = session['USER_AUTHORIZED']
-            agency = Agency(self.db_pool)
+            agency = Agency()
             fields = {
-                'ka_name': agency.getName(), 
-                'vorname': user.first_name,
+                'ka_name':  agency.getName(), 
+                'vorname':  user.first_name,
                 'nachname': user.last_name,
-                'fkz': agency.getFKZ(), 
-                'id': self.id
+                'fkz':      agency.getFKZ(), 
+                'id':       self.id
                 }
-            conn = self.db_pool.getConnection()
+            conn = db.getConnection()
             cur = conn.cursor()
             cur.execute(INIT_AGENCY_SQL, fields)
             conn.commit()
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if conn:
-                    self.db_pool.recycleConnection(conn)
-            except:
-                pass
-        
+            db.recycleConnection(conn, cur)
 
     def createDependencies(self):
-        #print >> sys.stderr, "createDependencies called"
         con, cur = None, None
         try:
-            con = self.db_pool.getConnection()
+            con = db.getConnection()
 
             # create one Kompetenzfestellung
             cur = con.cursor()
@@ -719,41 +619,28 @@
 
             con.commit()
         finally:
-            if cur:
-                try: cur.close()
-                except: pass
-            if con:
-                try: self.db_pool.recycleConnection(con)
-                except:pass
-                
+            db.recycleConnection(con, cur)
 
     def delete(self):
-        conn = None
-        cur = None
+        conn, cur = None, None
         try:
             try:
-                conn = self.db_pool.getConnection()
+                conn = db.getConnection()
                 cur = conn.cursor()
                 sql = DELETE_DS_SQL % int(self.id)
                 cur.execute(sql)
                 conn.commit()
                 return True
             finally:
-                try:
-                    if cur:
-                        cur.close()
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
-        except StandardError, err:
-            print >> sys.stderr, "Fehler beim Loeschen: %s" %str(err)
+                db.recycleConnection(conn, cur)
+        except:
+            traceback.print_exc(file=sys.stderr)
         return False 
 
 class DSFactory:
 
-    def __init__(self, dbpool):
-        self.dbpool = dbpool 
+    def __init__(self):
+        pass
 
     def getDataset(self, id):
         return None
@@ -762,11 +649,10 @@
         return 0
 
     def listDatasetIds(self, search_str=None, limit=None, ofs=None):
-        con = None
-        cur = None
+        con, cur = None, None
         ids = []
         try:
-            con = self.dbpool.getConnection()
+            con = db.getConnection()
             cur = con.cursor()
             if search_str:
                 fields = {'needle': search_str}
@@ -777,29 +663,23 @@
             for r in result:
                 ids.append(r[0])
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if con:
-                    self.db_pool.recycleConnection(con)
-            except:
-                pass
+            db.recycleConnection(con, cur)
         return ids 
 
     def createDataset(self):
         try:
-            ds = Dataset(self.dbpool)
+            ds = Dataset()
             ds_id = ds.create()
             return ds
         except StandardError, err:
             print >> sys.stderr, "Fehler beim Anlegen eines Datensatzes: %s" % str(err)
         return None 
 
-def kompetenzId(dbPool, id):
+def kompetenzId(id):
     con, cur = None, None
     result = None
     try:
-        con = dbPool.getConnection()
+        con = db.getConnection()
         # a master dataset has to be created each time
         cur = con.cursor()
         cur.execute(FETCH_KOMPETENZ_ID, { 'id': id })
@@ -808,32 +688,22 @@
             result = row[0]
         cur.close(); cur = None
     finally:
-        if cur:
-            try: cur.close()
-            except: pass
-        if con:
-            try: dbPool.recycleConnection(con)
-            except: pass
+        db.recycleConnection(con, cur)
     return result
 
 CASE_EXISTS = "SELECT * FROM case_exists(%(knummer)s)"
 
-def caseExists(dbPool, knummer):
+def caseExists(knummer):
     con, cur = None, None
     try:
-        con = dbPool.getConnection()
+        con = db.getConnection()
         cur = con.cursor()
         cur.execute(CASE_EXISTS, { 'knummer': knummer })
         row = cur.fetchone()
         if row is None: return False
         return row[0]
     finally:
-        if cur:
-            try: cur.close()
-            except: pass
-        if con:
-            try: dbPool.recycleConnection(con)
-            except: pass
+        db.recycleConnection(con, cur)
 
 CREATE_SQL = {
    'rg_angebote_bildenden_bereich_tbl':         CREATE_RG_BILDEN_DS,
@@ -842,13 +712,13 @@
    'rg_angebote_berufsvorbereitung_tbl':        CREATE_RG_BERUF_DS
 }
 
-def createTables(dbPool, relations):
+def createTables(relations):
     masterId, kompetenzId = None, None
 
     con, cur = None, None
     createdTables = {}
     try:
-        con = dbPool.getConnection()
+        con = db.getConnection()
         # a master dataset has to be created each time
         cur = con.cursor()
         cur.execute(CREATE_DS_SQL)
@@ -888,12 +758,7 @@
             if not separate:
                 createdTables[name] = id
     finally:
-        if cur:
-            try: cur.close()
-            except: pass
-        if con:
-            try: dbPool.recycleConnection(con)
-            except: pass
+        db.recycleConnection(con, cur)
 
     return masterId
 

Added: trunk/waskaweb/lib/db.py
===================================================================
--- trunk/waskaweb/lib/db.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/lib/db.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -0,0 +1,70 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2007 by Intevation GmbH
+# Authors:
+# Sascha L. Teichmann <teichmann at intevation.de>
+#
+from paste.registry import StackedObjectProxy
+
+import psycopg2 as dbapi
+
+import sys
+import traceback
+
+db = StackedObjectProxy(name="waska.db")
+
+def enter(dbObject):
+    db._push_object(dbObject)
+
+def leave(dbObject=None):
+    db._pop_object(dbObject)
+
+class DB:
+    def __init__(self, dbname, user, password, host='localhost', port=5432):
+        self.dbname      = dbname 
+        self.user        = user
+        self.password    = password
+        self.host        = host
+        self.port        = int(port)
+        self.conn        = None
+        self.connections = []
+
+    def getConnection(self):
+        for used in self.connections:
+            if not used[0]:
+                used[0] = True
+                return used[1]
+
+        con = dbapi.connect(
+            database = self.dbname,
+            host     = self.host,
+            port     = self.port,
+            user     = self.user,
+            password = self.password)
+        used = [True, con]
+        self.connections.append(used)
+        return con
+
+    def recycleConnection(self, con, cur=None):
+        if cur:
+            try: cur.close()
+            except: pass
+        if con:
+            for used in self.connections:
+                if used[1] == con:
+                    used[0] = False
+                    return
+            print >> sys.stderr, "WARNING: tried to recycle unused connection"
+
+    def closeConnections(self):
+        cons = self.connections
+        self.connections = []
+        for used in cons:
+            if used[0]:
+                print >> sys.stderr, "WARNING: Closing an unrecylcled connection"
+            try:
+                used[0].close()
+            except:
+                pass
+
+# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:

Deleted: trunk/waskaweb/lib/db_factory.py
===================================================================
--- trunk/waskaweb/lib/db_factory.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/lib/db_factory.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -1,50 +0,0 @@
-# -*- coding: latin1 -*-
-#
-# Copyright (c) 2007 by Intevation GmbH
-# Authors:
-# Sascha L. Teichmann <teichmann at intevation.de>
-
-import psycopg2 as dbapi
-
-import sys
-import traceback
-
-class DBPool:
-
-    def __init__(self, dbname, user, password, host='localhost', port=5432):
-        self.dbname   = dbname 
-        self.user     = user
-        self.password = password
-        self.host     = host
-        self.port     = int(port)
-        self.conn     = None
-
-    def getConnection(self):
-        conn = self.conn
-        if conn:
-            self.conn = None
-            return conn
-        try:
-            conn = dbapi.connect(
-                database = self.dbname,
-                host     = self.host,
-                port     = self.port,
-                user     = self.user,
-                password = self.password)
-            self.conn = conn
-        except:
-            traceback.print_exc(file=sys.stderr)
-            return None
-        return conn
-
-    def recycleConnection(self, conn):
-        self.conn = conn
-
-    def closeConnection(self):
-        conn = self.conn
-        if conn:
-            try: self.conn.close()
-            except dbapi.Error: pass
-            self.conn = None
-
-# vim:set ts=4 sw=4 si et sta sts=4 fenc=latin1:

Modified: trunk/waskaweb/lib/evaluation.py
===================================================================
--- trunk/waskaweb/lib/evaluation.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/lib/evaluation.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -3,31 +3,29 @@
 import codecs
 import waskaweb.lib.helpers as h
 import sys
+import traceback
 
 import cStringIO as StringIO
 
+from waskaweb.lib.db import db
+
 class Evaluation:
-    def __init__(self, conn):
+    def __init__(self):
         self.total = 0;
         self.total_cm = 0;
-        self.conn = conn
-        c1 = None
+        conn, c1 = None, None
         try:
             try:
-                c1 = self.conn.cursor()
+                conn = db.getConnection()
+                c1 = conn.cursor()
                 c1.execute("""SELECT getTotalCM()""")
                 self.total_cm = c1.fetchone()[0]
-                c1.close()
-                c1 = self.conn.cursor()
+                c1.close(); c1 = None
+                c1 = conn.cursor()
                 c1.execute("""SELECT getTotal()""")
                 self.total = c1.fetchone()[0]
-                c1.close()
             finally:
-                try:
-                    if c1:
-                        c1.close()
-                except:
-                    pass
+                db.recycleConnection(conn, c1)
         except:
             print >> sys.stderr, "Error! Could not get connection in evaluation"
 
@@ -55,15 +53,16 @@
         pass
 
 class Evaluation_1(Evaluation):
-    def __init__(self, conn):
-        Evaluation.__init__(self, conn)
+    def __init__(self):
+        Evaluation.__init__(self)
         self.percent = 0 
 
     def perform(self):
         try:
             if self.total == 0: divisor = 1
             else: divisor = self.total
-            self.percent = "%s" % h.formatNumber(float(self.total_cm)/float(divisor)*100)
+            self.percent = "%s" % h.formatNumber(
+                float(self.total_cm)/float(divisor)*100)
         except:
             print >> sys.stderr, "No results for eval 1"
             self.percent = 0;
@@ -76,8 +75,8 @@
         f.write(u"In das CM übernommen;%s;%s%%\n" %(self.total_cm, self.percent))
 
 class Evaluation_2(Evaluation):
-    def __init__(self, conn):
-        Evaluation.__init__(self, conn)
+    def __init__(self):
+        Evaluation.__init__(self)
 
     def perform(self):
         self.m = [0,0] 
@@ -85,32 +84,39 @@
         self.i = [0,0]
         self.u = [0,0]
 
-        cur = None
+        conn, cur = None, None
         try:
-            cur = self.conn.cursor()
-            sql = """SELECT count(geschlecht), geschlecht, g.value 
-                FROM master_tbl_eval_incm_view v 
-                JOIN geschlecht_tbl g ON v.geschlecht = g.id 
-                GROUP BY geschlecht, g.value"""
-            cur.execute(sql)
-            for g in cur.fetchall():
-                if g[1] == 1:
-                    self.m[0] = g[0]
-                elif g[1]== 0:
-                    self.w[0] = g[0]
-                elif g[1] == 2:
-                    self.i[0] = g[0]
-                else:
-                    self.u[0] = g[0]
-            self.total = self.m[0]+self.w[0]+self.i[0]+self.u[0]
-            if self.total > 0:
-                if self.total == 0: divisor = 1
-                else: divisor = self.total_cm
-                self.m[1] = "%s" % h.formatNumber(float(self.m[0])/float(divisor)*100)
-                self.w[1] = "%s" % h.formatNumber(float(self.w[0])/float(divisor)*100)
-                self.i[1] = "%s" % h.formatNumber(float(self.i[0])/float(divisor)*100)
-                self.u[1] = "%s" % h.formatNumber(float(self.u[0])/float(divisor)*100)
-            cur.close()
+            try:
+                conn = db.getConnection()
+                cur = conn.cursor()
+                sql = """SELECT count(geschlecht), geschlecht, g.value 
+                    FROM master_tbl_eval_incm_view v 
+                    JOIN geschlecht_tbl g ON v.geschlecht = g.id 
+                    GROUP BY geschlecht, g.value"""
+                cur.execute(sql)
+                for g in cur.fetchall():
+                    if g[1] == 1:
+                        self.m[0] = g[0]
+                    elif g[1]== 0:
+                        self.w[0] = g[0]
+                    elif g[1] == 2:
+                        self.i[0] = g[0]
+                    else:
+                        self.u[0] = g[0]
+                self.total = self.m[0]+self.w[0]+self.i[0]+self.u[0]
+                if self.total > 0:
+                    if self.total == 0: divisor = 1
+                    else: divisor = self.total_cm
+                    self.m[1] = "%s" % h.formatNumber(
+                        float(self.m[0])/float(divisor)*100)
+                    self.w[1] = "%s" % h.formatNumber(
+                        float(self.w[0])/float(divisor)*100)
+                    self.i[1] = "%s" % h.formatNumber(
+                        float(self.i[0])/float(divisor)*100)
+                    self.u[1] = "%s" % h.formatNumber(
+                        float(self.u[0])/float(divisor)*100)
+            finally:
+                db.recycleConnection(conn, cur)
         except:
             print >> sys.stderr, "No result for eval 2"
         return (self.total,self.m,self.w,self.i)
@@ -124,28 +130,29 @@
 
 class Evaluation_3(Evaluation):
     """Migrationshintergrund"""
-    def __init__(self, conn):
-        Evaluation.__init__(self, conn)
+    def __init__(self):
+        Evaluation.__init__(self)
 
     def perform(self):
-        c1 = self.conn.cursor()
-        m = [0,0]
-        sql = """select count(id) from master_tbl_eval_incm_view 
-                    WHERE geburtsland <> 29 
-                    OR vater = 0 
-                    OR mutter = 0"""
         try:
-            c1.execute(sql)
-        except StandardError, err:
-            print >> sys.stderr,  "can not select: %s" % str(err)
-        try:
-            m[0] = c1.fetchone()[0]
-            if m[0]:
-                m[1] = "%s" % h.formatNumber(float(m[0])/float(self.total_cm)*100)
-            c1.close()
+            conn, c1 = None, None
+            try:
+                conn = db.getConnection()
+                c1 = conn.cursor()
+                m = [0,0]
+                sql = """select count(id) from master_tbl_eval_incm_view 
+                         WHERE geburtsland <> 29 
+                         OR vater = 0 
+                         OR mutter = 0"""
+                c1.execute(sql)
+                m[0] = c1.fetchone()[0]
+                if m[0]:
+                    m[1] = "%s" % h.formatNumber(
+                        float(m[0])/float(self.total_cm)*100)
+            finally:
+                db.recycleConnection(conn, c1)
         except StandardError, err: 
             print >> sys.stderr,  "no result eval 3: %s" % str(err)
-            c1.close()
             return [0,0]
         return m 
 
@@ -156,11 +163,10 @@
 
 class Evaluation_4(Evaluation):
     """ Zugang der der Jugendichen zu KA"""
-    def __init__(self, conn):
-        Evaluation.__init__(self, conn)
+    def __init__(self):
+        Evaluation.__init__(self)
 
     def perform(self):
-        c1 = self.conn.cursor()
         result = {}
         sql = """select t.id, count(v.zugang_kompetenzagentur), t.value 
                     from master_tbl_view v 
@@ -169,24 +175,31 @@
                     group by t.id, t.value having t.id is not null 
                     order by t.id asc"""
         try:
-            c1.execute(sql)
-        except StandardError, err:
-            print >> sys.stderr,  "can not select: %s" % str(err)
-        try:
-            if self.total == 0: divisor = 1
-            else: divisor = self.total
-            for r in c1.fetchall():
-                result[r[0]] = []
-                try:
-                    result[r[0]].append(u'%s' % unicode(r[2], 'utf-8')) # name
-                    result[r[0]].append(r[1]) # how many?
-                    result[r[0]].append("%s" % h.formatNumber(float(r[1])/float(divisor)*100))
-                except StandardError, err:
-                    print >> sys.stderr, str(err)
-            c1.close()
+            conn, c1 = None, None
+            try:
+                conn = db.getConnection()
+                c1 = conn.cursor()
+                c1.execute(sql)
+
+                if self.total == 0: divisor = 1
+                else: divisor = self.total
+
+                for r in c1.fetchall():
+                    result[r[0]] = []
+                    try:
+                        result[r[0]].append(
+                            u'%s' % unicode(r[2], 'utf-8')) # name
+                        result[r[0]].append(
+                            r[1]) # how many?
+                        result[r[0]].append(
+                            "%s" % h.formatNumber(
+                                float(r[1])/float(divisor)*100))
+                    except StandardError, err:
+                        print >> sys.stderr, str(err)
+            finally:
+                db.recycleConnection(con, c1)
         except:
             print >> sys.stderr, "No results for eval 4"
-            c1.close()
         return result 
 
     def doExport(self, f):
@@ -197,11 +210,10 @@
 
 class Evaluation_5(Evaluation):
     """Rechtskreis der Jugendlichen beim Zugang zur KA"""
-    def __init__(self, conn):
-        Evaluation.__init__(self, conn)
+    def __init__(self):
+        Evaluation.__init__(self)
 
     def perform(self):
-        c1 = self.conn.cursor()
         result = {}
         sql = """select r.id, count(m.rechtlicher_kontext), r.value from master_tbl_view m 
                     right join rechtlicher_kontext_tbl r 
@@ -209,24 +221,28 @@
                     group by r.id, r.value having r.id is not null
                     order by r.id asc"""
         try:
-            c1.execute(sql)
+            conn, c1 = None, None
+            try:
+                conn = db.getConnection()
+                c1 = conn.cursor()
+                c1.execute(sql)
+                if self.total == 0: divisor = 1
+                else: divisor = self.total
+                for r in c1.fetchall():
+                    result[r[0]] = []
+                    try:
+                        result[r[0]].append(
+                            u'%s' % unicode(r[2], 'utf-8')) # name
+                        result[r[0]].append(r[1]) # how many?
+                        result[r[0]].append(
+                            "%s" % h.formatNumber(
+                                float(r[1])/float(divisor)*100))
+                    except StandardError, err:
+                        print >> sys.stderr, str(err)
+            finally:
+                db.recycleConnection(conn, c1)
         except StandardError, err:
-            print >> sys.stderr, str('Can not Select: %s' % err)
-        try:
-            if self.total == 0: divisor = 1
-            else: divisor = self.total
-            for r in c1.fetchall():
-                result[r[0]] = []
-                try:
-                    result[r[0]].append(u'%s' % unicode(r[2], 'utf-8')) # name
-                    result[r[0]].append(r[1]) # how many?
-                    result[r[0]].append("%s" % h.formatNumber(float(r[1])/float(divisor)*100))
-                except StandardError, err:
-                    print >> sys.stderr, str(err)
-            c1.close()
-        except StandardError, err:
             print >> sys.stderr, str('no results for eval 5: %s' % err)
-            c1.close()
         return result 
 
     def doExport(self, f):
@@ -237,37 +253,42 @@
 
 class Evaluation_6(Evaluation):
     """Vermittlung nach Beendigung"""
-    def __init__(self, conn):
-        Evaluation.__init__(self, conn)
+    def __init__(self):
+        Evaluation.__init__(self)
 
     def perform(self):
-        c1 = self.conn.cursor()
         result = {}
         sql = """select v.id, count(m.vermittlung), v.value from master_tbl_eval_incm_view m 
                     right join vermittlung_tbl v on m.vermittlung = v.id 
                     group by v.id, v.value having v.id is not null order by v.id asc"""
         try:
-            c1.execute(sql)
-        except:
-            print >> sys.stderr, str('Can not Select')
-        try:
-            if self.total == 0: divisor = 1
-            else: divisor = self.total_cm
-            for r in c1.fetchall():
-                result[r[0]] = []
-                try:
-                    result[r[0]].append(u'%s' % unicode(r[2], "utf-8")) # name
-                    result[r[0]].append(r[1]) # how many?
+            conn, c1 = None, None
+            try:
+                conn = db.getConnection()
+                c1 = conn.cursor()
+                c1.execute(sql)
+                if self.total == 0: divisor = 1
+                else: divisor = self.total_cm
+                for r in c1.fetchall():
+                    result[r[0]] = []
                     try:
-                        result[r[0]].append("%s" % h.formatNumber(float(r[1])/float(divisor)*100))
-                    except:
-                        result[r[0]].append("%s" % h.formatNumber(0.0))
-                except StandardError, err:
-                    print >> sys.stderr, str('Error on assigning values: %s' % err)
-            c1.close()
+                        result[r[0]].append(
+                            u'%s' % unicode(r[2], "utf-8")) # name
+                        result[r[0]].append(
+                            r[1]) # how many?
+                        try:
+                            result[r[0]].append(
+                                "%s" % h.formatNumber(
+                                    float(r[1])/float(divisor)*100))
+                        except:
+                            result[r[0]].append("%s" % h.formatNumber(0.0))
+                    except StandardError, err:
+                        print >> sys.stderr, str(
+                            'Error on assigning values: %s' % err)
+            finally:
+                db.recycleConnection(conn, c1)
         except StandardError, err:
             print >> sys.stderr, str('No result eval 6: %s' % err)
-            c1.close()
         return result 
 
     def doExport(self, f):
@@ -278,38 +299,43 @@
 
 class Evaluation_7(Evaluation):
     """Rechtskreis nach Vermittlung"""
-    def __init__(self, conn):
-        Evaluation.__init__(self, conn)
+    def __init__(self):
+        Evaluation.__init__(self)
 
     def perform(self):
-        c1 = self.conn.cursor()
         result = {}
         sql = """select r.id, count(m.veraenderungen_rechtskreis), r.value from master_tbl_eval_incm_view m 
                     right join rechtlicher_kontext_tbl r 
                     on m.veraenderungen_rechtskreis = r.id 
                     group by r.id, r.value having r.id is not null order by r.id asc"""
         try:
-            c1.execute(sql)
-        except:
-            print >> sys.stderr, str('Can not Select')
-        try:
-            if self.total == 0: divisor = 1
-            else: divisor = self.total_cm
-            for r in c1.fetchall():
-                result[r[0]] = []
-                try:
-                    result[r[0]].append(u'%s' % unicode(r[2], "utf-8")) # name
-                    result[r[0]].append(r[1]) # how many?
+            conn, c1 = None, None
+            try:
+                conn = db.getConnection()
+                c1 = conn.cursor()
+                c1.execute(sql)
+                if self.total == 0: divisor = 1
+                else: divisor = self.total_cm
+                for r in c1.fetchall():
+                    result[r[0]] = []
                     try:
-                        result[r[0]].append("%s" % h.formatNumber(float(r[1])/float(divisor)*100))
-                    except:
-                        result[r[0]].append("%s" % h.formatNumber(0.0))
-                except StandardError, err:
-                    print >> sys.stderr, str('Error on assigning values: %s' % err)
-            c1.close()
+                        result[r[0]].append(
+                            u'%s' % unicode(r[2], "utf-8")) # name
+                        result[r[0]].append(
+                            r[1]) # how many?
+                        try:
+                            result[r[0]].append(
+                                "%s" % h.formatNumber(
+                                    float(r[1])/float(divisor)*100))
+                        except:
+                            result[r[0]].append("%s" % h.formatNumber(0.0))
+                    except StandardError, err:
+                        print >> sys.stderr, str(
+                            'Error on assigning values: %s' % err)
+            finally:
+                db.recycleConnection(conn, c1)
         except StandardError, err:
             print >> sys.stderr, str('No results for eval 7: %s' % err)
-            c1.close()
         return result 
 
     def doExport(self, f):
@@ -320,11 +346,10 @@
 
 class Evaluation_8(Evaluation):
     """Altersvreteilung"""
-    def __init__(self, conn):
-        Evaluation.__init__(self, conn)
+    def __init__(self):
+        Evaluation.__init__(self)
 
     def perform(self):
-        c1 = self.conn.cursor()
         result = [["<14",0,0], 
                 ["14-16",0,0],  
                 ["16-18",0,0], 
@@ -333,41 +358,51 @@
                 ["24-27",0,0], 
                 [">27",0,0]]
         try:
-            c1.execute("""select date_part('year', age(geburtsdatum::timestamp)) from master_tbl_eval_incm_view""")
-        except:
-            print >> sys.stderr, str('Can not Select')
-        try:
-            if self.total == 0: divisor = 1
-            else: divisor = self.total_cm
-            for r in c1.fetchall():
-                #TODO Filter empty rows in sql directly
-                if not r[0]: 
-                    continue
-                if r[0] < 14:
-                    result[0][1] += 1
-                    result[0][2] = "%s" % h.formatNumber(float(result[0][1])/float(divisor)*100)
-                if 14 <= r[0] <= 16:
-                    result[1][1] += 1
-                    result[1][2] = "%s" % h.formatNumber(float(result[1][1])/float(divisor)*100)
-                if 16 < r[0] <= 18:
-                    result[2][1] += 1
-                    result[2][2] = "%s" % h.formatNumber(float(result[2][1])/float(divisor)*100)
-                if 18 < r[0] <= 21:
-                    result[3][1] += 1
-                    result[3][2] = "%s" % h.formatNumber(float(result[3][1])/float(divisor)*100)
-                if 21 < r[0] <= 24:
-                    result[4][1] += 1
-                    result[4][2] = "%s" % h.formatNumber(float(result[4][1])/float(divisor)*100)
-                if 24 < r[0] <= 27:
-                    result[5][1] += 1
-                    result[5][2] = "%s" % h.formatNumber(float(result[5][1])/float(divisor)*100)
-                if 27 < r[0]:
-                    result[6][1] += 1
-                    result[6][2] = "%s" % h.formatNumber(float(result[6][1])/float(divisor)*100)
-            c1.close()
+            conn, c1 = None, None
+            try:
+                conn = db.getConnection()
+                c1 = conn.cursor()
+                c1.execute(
+                    """select date_part('year', age(geburtsdatum::timestamp)) 
+                       from master_tbl_eval_incm_view""")
+                if self.total == 0: divisor = 1
+                else: divisor = self.total_cm
+                for r in c1.fetchall():
+                    #TODO Filter empty rows in sql directly
+                    if not r[0]: 
+                        continue
+                    if r[0] < 14:
+                        result[0][1] += 1
+                        result[0][2] = "%s" % h.formatNumber(
+                            float(result[0][1])/float(divisor)*100)
+                    if 14 <= r[0] <= 16:
+                        result[1][1] += 1
+                        result[1][2] = "%s" % h.formatNumber(
+                            float(result[1][1])/float(divisor)*100)
+                    if 16 < r[0] <= 18:
+                        result[2][1] += 1
+                        result[2][2] = "%s" % h.formatNumber(
+                            float(result[2][1])/float(divisor)*100)
+                    if 18 < r[0] <= 21:
+                        result[3][1] += 1
+                        result[3][2] = "%s" % h.formatNumber(
+                            float(result[3][1])/float(divisor)*100)
+                    if 21 < r[0] <= 24:
+                        result[4][1] += 1
+                        result[4][2] = "%s" % h.formatNumber(
+                            float(result[4][1])/float(divisor)*100)
+                    if 24 < r[0] <= 27:
+                        result[5][1] += 1
+                        result[5][2] = "%s" % h.formatNumber(
+                            float(result[5][1])/float(divisor)*100)
+                    if 27 < r[0]:
+                        result[6][1] += 1
+                        result[6][2] = "%s" % h.formatNumber(
+                            float(result[6][1])/float(divisor)*100)
+            finally:
+                db.recycleConnection(conn, c1)
         except StandardError, err:
             print >> sys.stderr, str('No results for eval 8: %s' % err)
-            c1.close()
         return result 
 
     def doExport(self, f):
@@ -378,48 +413,60 @@
 
 class Evaluation_9(Evaluation):
     """Verteilung Foerderangebote"""
-    def __init__(self, conn):
-        Evaluation.__init__(self, conn)
+    def __init__(self):
+        Evaluation.__init__(self)
 
     def perform(self):
-        c1 = self.conn.cursor()
         result = [[u"berufliche Qualifizierung",0,0],
             [u"berufliche Vorbereitung", 0,0],
             [u"bildenden Bereich", 0,0],
             [u"%s" % unicode("Lebens- bewältigung", "utf-8"), 0,0]
         ]
         try:
-            c1.execute("""select count(id) from rg_angebote_berufliche_qualifizierung_tbl_view""")
-            result[0][1] = c1.fetchone()[0]
-            c1.close()
-            c1 = self.conn.cursor()
-            c1.execute("""select count(id) from rg_angebote_berufsvorbereitung_tbl_view""")
-            result[1][1] = c1.fetchone()[0]
-            c1.close()
-            c1 = self.conn.cursor()
-            c1.execute("""select count(id) from rg_angebote_bildenden_bereich_tbl_view""")
-            result[2][1] = c1.fetchone()[0]
-            c1.close()
-            c1 = self.conn.cursor()
-            c1.execute("""select count(id) from rg_angebote_lebensbewaeltigung_tbl_view""")
-            result[3][1] = c1.fetchone()[0]
-            c1.close()
-            c1 = self.conn.cursor()
-            
-            total = 0
-            # Gesammtanzahl der Maßnahmen berechnen
-            for r in result: total += r[1]
-            if total == 0: total = 1
-            result[0][2] = "%s" % h.formatNumber(float(result[0][1])/float(total)*100)
-            result[1][2] = "%s" % h.formatNumber(float(result[1][1])/float(total)*100)
-            result[2][2] = "%s" % h.formatNumber(float(result[2][1])/float(total)*100)
-            result[3][2] = "%s" % h.formatNumber(float(result[3][1])/float(total)*100)
-            c1.close()
-            c1 = None
+            conn, c1 = None, None
+            try:
+                conn = db.getConnection()
+                c1 = conn.cursor()
+                c1.execute(
+                    """select count(id) 
+                       from rg_angebote_berufliche_qualifizierung_tbl_view""")
+                result[0][1] = c1.fetchone()[0]
+                c1.close(); c1 = None
+                c1 = conn.cursor()
+                c1.execute(
+                    """select count(id) 
+                       from rg_angebote_berufsvorbereitung_tbl_view""")
+                result[1][1] = c1.fetchone()[0]
+                c1.close(); c1 = None
+                c1 = conn.cursor()
+                c1.execute(
+                    """select count(id)
+                       from rg_angebote_bildenden_bereich_tbl_view""")
+                result[2][1] = c1.fetchone()[0]
+                c1.close(); c1 = None
+                c1 = conn.cursor()
+                c1.execute(
+                    """select count(id)
+                       from rg_angebote_lebensbewaeltigung_tbl_view""")
+                result[3][1] = c1.fetchone()[0]
+                c1.close(); c1 = None
+                
+                total = 0
+                # Gesammtanzahl der Maßnahmen berechnen
+                for r in result: total += r[1]
+                if total == 0: total = 1
+                result[0][2] = "%s" % h.formatNumber(
+                    float(result[0][1])/float(total)*100)
+                result[1][2] = "%s" % h.formatNumber(
+                    float(result[1][1])/float(total)*100)
+                result[2][2] = "%s" % h.formatNumber(
+                    float(result[2][1])/float(total)*100)
+                result[3][2] = "%s" % h.formatNumber(
+                    float(result[3][1])/float(total)*100)
+            finally:
+                db.recycleConnection(conn, c1)
         except StandardError, err:
             print >> sys.stderr, str('No results for eval 9: %s' % err)
-            if c1:
-                c1.close()
         return result
 
     def doExport(self, f):
@@ -430,40 +477,51 @@
 
 class Evaluation_10(Evaluation):
     """Verweildauer im CM"""
-    def __init__(self, conn):
-        Evaluation.__init__(self, conn)
+    def __init__(self):
+        Evaluation.__init__(self)
 
     def perform(self):
         # [monat, abgeschl_num, abschloss_proz, abbruch_num, abbruch_proz]
-        c1 = self.conn.cursor()
-        sql = """select count(id), art_beendigung, zeitraum_fallmanagement from master_tbl_eval_incm_view where art_beendigung <> -1 group by zeitraum_fallmanagement, art_beendigung"""
-        c1.execute(sql)
+        sql = """select count(id), art_beendigung, zeitraum_fallmanagement 
+                 from master_tbl_eval_incm_view 
+                 where art_beendigung <> -1 
+                 group by zeitraum_fallmanagement, art_beendigung"""
+        result = []
         row = None
-        result = []
-        curr_month = -1
-        if self.total_cm == 0: divisor = 1
-        else: divisor = self.total_cm
-        for r in c1.fetchall():
-            if r[1] == '-1': # Keine Angabe
-                continue
-            
-            if r[2] != curr_month:
-                curr_month = r[2]
-                if row is not None:
-                    if row[1] != 0 or row[3] != 0:
-                        result.append(row)
-                row = [r[2],0,0,0,0]
+        try:
+            conn, c1 = None, None
+            try:
+                conn = db.getConnection()
+                c1 = conn.cursor()
+                c1.execute(sql)
+                curr_month = -1
+                if self.total_cm == 0: divisor = 1
+                else: divisor = self.total_cm
+                for r in c1.fetchall():
+                    if r[1] == '-1': # Keine Angabe
+                        continue
+                    
+                    if r[2] != curr_month:
+                        curr_month = r[2]
+                        if row is not None:
+                            if row[1] != 0 or row[3] != 0:
+                                result.append(row)
+                        row = [r[2],0,0,0,0]
 
-            num = r[0]
-            proz = "%s" % h.formatNumber(float(r[0])/float(divisor)*100)
+                    num = r[0]
+                    proz = "%s" % h.formatNumber(float(r[0])/float(divisor)*100)
 
-            if r[1] == 1 : # Abbruch
-                row[3] = num
-                row[4] = proz 
-            else: 
-                row[1] = num
-                row[2] = proz 
-        c1.close()
+                    if r[1] == 1 : # Abbruch
+                        row[3] = num
+                        row[4] = proz 
+                    else: 
+                        row[1] = num
+                        row[2] = proz 
+            finally:
+                db.recycleConnection(conn, c1)
+        except:
+            traceback.print_exc(file=sys.stderr)
+
         if row is not None:
             result.append(row)
         return result

Modified: trunk/waskaweb/lib/helpers.py
===================================================================
--- trunk/waskaweb/lib/helpers.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/lib/helpers.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -7,7 +7,6 @@
 import locale
 from pylons import c, cache, config, g, request, response, session
 from webhelpers import *
-from waskaweb.lib.db_factory import *
 
 def hasRole(rolelist):
     # available rolenames:

Modified: trunk/waskaweb/lib/security.py
===================================================================
--- trunk/waskaweb/lib/security.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/lib/security.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -6,7 +6,7 @@
 # Torsten Irlaender <torsten.irlaender at intevation.de>
 #
 
-from waskaweb.lib.db_factory import *
+from waskaweb.lib.db import DB, db, enter, leave
 from pylons import request, session
 import re
 import traceback
@@ -27,46 +27,50 @@
     if not check_re.match(user) or not check_re.match(dbname):
         return None
 
-    db_pool = None
     try:
+        mydb = DB(
+            dbname   = DBNAME % dbname,
+            host     = HOST,
+            port     = PORT,
+            user     = USER % (dbname, user),
+            password = password)
+
         try:
-            db_pool = DBPool(
-                dbname   = DBNAME % dbname,
-                host     = HOST,
-                port     = PORT,
-                user     = USER % (dbname, user),
-                password = password)
+            enter(mydb)
+            conn, cursor = None, None
+            try:
+                conn = db.getConnection()
+                cursor = conn.cursor()
+                cursor.execute(ROLE_SQL)
+                try:
+                    # Get role of the current logged in user
+                    result = cursor.fetchone()[0]
+                    tok = result.split('_')
+                    role = "_".join(tok[-2:])
+                except:
+                    print >> sys.stderr, "No role found"
+                    role = None
+            finally:
+                db.recycleConnection(conn, cursor)
 
-            conn = db_pool.getConnection()
-            cursor = conn.cursor()
-            cursor.execute(ROLE_SQL)
             try:
-                # Get role of the current logged in user
-                result = cursor.fetchone()[0]
-                tok = result.split('_')
-                role = "_".join(tok[-2:])
-            except:
-                print "No role found"
-                role = None
-            cursor.close()
-            try:
                 from waskaweb.model.user import UserObject 
-                userobject = UserObject(db_pool)
+                userobject = UserObject()
                 if user == 'adm':
                     userobject.setAdmUser()
                 else:
                     userobject.loadByName(user)
                     userobject.role = role
+
+                return userobject
             except StandardError, err:
+                traceback.print_exc(file=sys.stderr)
                 print "Error on creating user Object: %s" % err
-            db_pool.recycleConnection(conn)
-            return userobject 
         finally:
-            if db_pool:
-                db_pool.closeConnection()
+            leave(mydb)
+            mydb.closeConnections()
     except: 
         traceback.print_exc(file=sys.stderr)
-        return None 
     return None 
 
 def getDbName():

Modified: trunk/waskaweb/lib/validators.py
===================================================================
--- trunk/waskaweb/lib/validators.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/lib/validators.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -69,9 +69,8 @@
     chained_validators = [formencode.validators.FieldsMatch('passwd', 'passwd2')]
 
 class NewUserForm(BaseFormValidator):
-    def __init__(self, db_pool):
+    def __init__(self):
         formencode.api.set_stdtranslation(domain="FormEncode", languages=["de"])
-        self.db_pool = db_pool
 
     firstname = formencode.validators.String(not_empty=True) 
     lastname = formencode.validators.String(not_empty=True) 

Modified: trunk/waskaweb/model/agency.py
===================================================================
--- trunk/waskaweb/model/agency.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/model/agency.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -11,81 +11,81 @@
 import traceback
 import sys
 
+from waskaweb.lib.db import db
+
 FETCH_SETTINGS_SQL = """SELECT bez, wert from ka_konfiguration_tbl_view"""
 STORE_SETTINGS_SQL = """UPDATE ka_konfiguration_tbl_view SET wert = %(wert)s WHERE bez = %(bez)s"""
+
 class Agency:
-    def __init__(self, db_pool):
-        self.db_pool = db_pool
+    def __init__(self):
         self.conf = {}
         self._fetchData()
 
     def _fetchData(self):
-        conn = None
-        cur = None
+        conn, cur = None, None
         try:
-            conn = self.db_pool.getConnection()
+            conn = db.getConnection()
             cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
             cur.execute(FETCH_SETTINGS_SQL)
             rows = cur.fetchall()
             for row in rows:
                 self.conf[row['bez']] = row['wert']
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if conn:
-                    self.db.recycleConnection(conn)
-            except:
-                pass
+            db.recycleConnection(conn, cur)
 
     def store(self, formdata):
         conn = None
-        cur = None
         try:
-            conn = self.db_pool.getConnection()
-            for key, value in formdata.iteritems():
-                try:
-                    cur = conn.cursor()
-                    cur.execute(STORE_SETTINGS_SQL, {'bez': key, 'wert': value})
-                    conn.commit()
-                    cur.close()
-                except:
-                    traceback.print_exc(file=sys.stderr)
-        finally:
             try:
-                if cur:
-                    cur.close()
-                if conn:
-                    self.db.recycleConnection(conn)
-            except:
-                pass
+                conn = db.getConnection()
+                for key, value in formdata.iteritems():
+                    cur = None
+                    try:
+                        cur = conn.cursor()
+                        cur.execute(STORE_SETTINGS_SQL, {'bez': key, 'wert': value})
+                        conn.commit()
+                    finally:
+                        if cur:
+                            try: cur.close()
+                            except: pass
+            finally:
+                db.recycleConnection(conn)
+        except:
+            traceback.print_exc(file=sys.stderr)
 
     def isAnonTransfer(self):
-        return self.conf.get('anon_trasfer', '') == '1'
+        return self.conf.get('anon_trasfer', '') == 'on'
 
     def getFKZ(self):
-        return self.conf.get('fkz', '')
+        return unicode(str(self.conf.get('fkz', '')), 'utf-8')
 
     def getName(self):
-        return self.conf.get('ka_name', '')
+        return unicode(str(self.conf.get('ka_name', '')), 'utf-8')
 
     def _loadDefaultStatement(self, filename):
         # XXX: Dead ugly!
         path = os.path.join(os.path.dirname(__file__), '..', '..', 'formed')
         path_statement = os.path.join(path, filename)
-        file = open(path_statement, "r")
-        statement = file.read()
-        file.close()
+        f = None
+        try:
+            f = open(path_statement, "r")
+            statement = f.read()
+        finally:
+            if f:
+                try: f.close()
+                except: pass
         return unicode(statement, 'utf-8') 
         
     def getAidPlanStatement(self):
         form = self.conf.get('fp_formular', '')
-        if len(form) > 0: return unicode(form, 'utf-8')
-        else: return self._loadDefaultStatement('aid_plan_statement.html')
+        if len(form) > 0:
+            return unicode(form, 'utf-8')
+        return self._loadDefaultStatement('aid_plan_statement.html')
 
     def getPrivacyStatement(self):
         form = self.conf.get('ee_formular', '')
-        if len(form) > 0: return unicode(form, 'utf-8')
-        else: return self._loadDefaultStatement('privacy_statement.html')
+        if len(form) > 0:
+            return unicode(form, 'utf-8')
+        return self._loadDefaultStatement('privacy_statement.html')
 
 # vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8:

Modified: trunk/waskaweb/model/document.py
===================================================================
--- trunk/waskaweb/model/document.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/model/document.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -10,6 +10,8 @@
 import psycopg2  as dbapi
 import cStringIO as StringIO
 
+from waskaweb.lib.db import db
+
 MAX_SIZE   = 10*1024*1024
 BLOCK_SIZE = 4*1024
 
@@ -67,7 +69,7 @@
     def __str__(self):
         return repr(self.value)
 
-def listDocuments(dbPool, case=None):
+def listDocuments(case=None):
 
     if not case is None: case = int(case)
 
@@ -75,7 +77,7 @@
 
     con, cur = None, None
     try:
-        con = dbPool.getConnection()
+        con = db.getConnection()
         cur = con.cursor()
         if case is None:
             cur.execute(LIST_GLOBAL)
@@ -88,20 +90,15 @@
             id, case, size, mime, name = row
             documents.append(Document(id, case, size, mime, name))
     finally:
-        if cur:
-            try: cur.close()
-            except: pass
-        if con:
-            try: dbPool.recycleConnection(con)
-            except: pass
+        db.recycleConnection(con, cur)
 
     return documents
 
-def deleteDocument(dbPool, id, case=False):
+def deleteDocument(id, case=False):
     id = int(id)
     con, cur, has_commited = None, None, False
     try:
-        con = dbPool.getConnection()
+        con = db.getConnection()
         cur = con.cursor()
         if case: cur.execute(DELETE_CASE,   { 'id': id })
         else:    cur.execute(DELETE_GLOBAL, { 'id': id })
@@ -112,12 +109,7 @@
             try: con.rollback()
             except: pass
 
-        if cur:
-            try: cur.close()
-            except: pass
-        if con:
-            try: dbPool.recycleConnection(con)
-            except: pass
+        db.recycleConnection(con, cur)
 
 class Document:
     def __init__(self, id=None, case=None, size=None, mime=None, name=None):
@@ -131,8 +123,15 @@
     def isCaseAttached(self):
         return not self.case is None
 
-    def create(self, dbPool, name, src, case=None):
+    def getName(self, encoding="utf-8"):
+        name = self.name
+        if name is None: return None
+        if encoding:
+            return unicode(str(name), encoding)
+        return name
 
+    def create(self, name, src, case=None):
+
         name = name.strip().rsplit('\\', 1)[-1].rsplit('/', 1)[-1]
 
         if not name:
@@ -169,7 +168,7 @@
         has_commited, con, cur = False, None, None
 
         try:
-            con = dbPool.getConnection()
+            con = db.getConnection()
             cur = con.cursor()
 
             if case is None: cur.execute(CREATE_GLOBAL)
@@ -208,16 +207,14 @@
                 try: con.rollback()
                 except: pass
 
-            if con:
-                try: dbPool.recycleConnection(con)
-                except: pass
+            db.recycleConnection(con)
 
-    def load(self, dbPool, asCase=False):
+    def load(self, asCase=False):
         if self.id is None:
             raise DocumentException(u"ID wird benötigt")
         con, cur = None, None
         try:
-            con = dbPool.getConnection()
+            con = db.getConnection()
             cur = con.cursor()
             if asCase: cur.execute(LOAD_CASE,   { 'id': self.id })
             else:      cur.execute(LOAD_GLOBAL, { 'id': self.id })
@@ -231,12 +228,6 @@
             self.data = row[3]
             self.name = row[4]
         finally:
-            if cur:
-                try: cur.close()
-                except: pass
-            if con:
-                try: dbPool.recycleConnection(db)
-                except: pass
+            db.recycleConnection(con, cur)
 
-
 # vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:

Modified: trunk/waskaweb/model/statement.py
===================================================================
--- trunk/waskaweb/model/statement.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/model/statement.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -5,13 +5,14 @@
 # Torsten Irländer <torsten.irlaender at intevation.de>
 #
 
+from waskaweb.lib.db import db
+
 from string import Template
 
 GET_STATEMENT_FLAG_SQL = """"""
 SET_STATEMENT_FLAG_SQL = """UPDATE page_einverstaendnis_view SET einverstaendniserklaerung = %(value)s WHERE id = %(id)s"""
 class Statement:
-    def __init__(self, db_pool, id=None):
-        self.db_pool = db_pool
+    def __init__(self, id=None):
         self.case_id = id
     
     def _substitute(self, client, agency):
@@ -30,8 +31,8 @@
         pass
 
 class PrivacyStatement(Statement):
-    def __init__(self, db_pool, id=None):
-        Statement.__init__(self, db_pool, id)
+    def __init__(self, id=None):
+        Statement.__init__(self, id)
 
     def fillout(self, client, agency, **kwargs):
         tmpl = agency.getPrivacyStatement()
@@ -52,42 +53,28 @@
         return result 
 
     def sign(self):
-        conn = None
-        cur = None
+        conn, cur = None, None
         try:
-            conn = self.db_pool.getConnection()
+            conn = db.getConnection()
             cur = conn.cursor()
             cur.execute(SET_STATEMENT_FLAG_SQL, {'id': self.case_id, 'value': 1})
             conn.commit()
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if conn:
-                    self.db.recycleConnection(conn)
-            except:
-                pass
+            db.recycleConnection(conn, cur)
 
     def decline(self):
-            conn = None
-            cur = None
+            conn, cur = None, None
             try:
-                conn = self.db_pool.getConnection()
+                conn = db.getConnection()
                 cur = conn.cursor()
                 cur.execute(SET_STATEMENT_FLAG_SQL, {'id': self.case_id, 'value': 0})
                 conn.commit()
             finally:
-                try:
-                    if cur:
-                        cur.close()
-                    if conn:
-                        self.db.recycleConnection(conn)
-                except:
-                    pass
+                db.recycleConnection(conn, cur)
 
 class AidPlanStatement(Statement):
-    def __init__(self, db_pool, id=None):
-        Statement.__init__(self, db_pool, id)
+    def __init__(self, id=None):
+        Statement.__init__(self, id)
 
     def fillout(self, client, agency, **kwargs):
         list = self._buildAidList(kwargs.get('rg_list', []))

Modified: trunk/waskaweb/model/user.py
===================================================================
--- trunk/waskaweb/model/user.py	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/model/user.py	2008-08-13 13:02:47 UTC (rev 8)
@@ -1,6 +1,7 @@
 import waskaweb.lib.helpers as h
 from waskaweb.lib.security import getDbName 
-from waskaweb.lib.db_factory import DBPool
+from waskaweb.lib.db import db
+
 from pylons import config, session
 import sys
 FETCH_USER_LIST_SQL = """SELECT id from ka_benutzer_tbl_view order by nachname""" 
@@ -16,26 +17,18 @@
 #GET_USERROLE_SQL = """select groname from pg_group where %(useroid)s = ANY (grolist)"""
 
 class UserListObject:
-    def __init__(self, db_pool):
+    def __init__(self):
         self.user = []
-        self.db_pool = db_pool
-        conn = None
-        cur = None
         try:
+            conn, cur = None, None
             try:
-                conn = self.db_pool.getConnection()
-                cur = conn.cursor()
+                conn = db.getConnection()
+                cur  = conn.cursor()
                 cur.execute(FETCH_USER_LIST_SQL)
                 for r in cur.fetchall():
-                    self.user.append(UserObject(self.db_pool, r[0]))
+                    self.user.append(UserObject(r[0]))
             finally:
-                try:
-                    if cur:
-                        cur.close()
-                    if conn:
-                        self.db_pool.recycleConnection(conn)
-                except:
-                    pass
+                db.recycleConnection(conn, cur)
         except StandardError, err:
             print >> sys.stderr, "Error on creating user overview: %s" % str(err)
 
@@ -53,8 +46,7 @@
             return self.user
         
 class UserObject:
-    def __init__(self, db_pool, id=None):
-        self.db_pool = db_pool
+    def __init__(self, id=None):
         
         self.login = ''
         self.role = '' 
@@ -119,10 +111,9 @@
             return role
 
     def setPassword(self, password):
-        conn = None
-        cur = None
+        conn, cur = None, None
         try:
-            conn = self.db_pool.getConnection()
+            conn = db.getConnection()
             cur = conn.cursor()
             fields = {'login': self.full_login, 'password': password}
             cur.execute(ALTER_USER_PASSWORD_SQL, fields)
@@ -131,46 +122,32 @@
             self.needs_passrefresh = False
             return new_pass 
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if conn:
-                    self.db_pool.recycleConnection(conn)
-            except:
-                pass
+            db.recycleConnection(conn, cur)
         return None 
 
     def resetPassword(self):
-        conn = None
-        cur = None
+        conn, cur = None, None
         password = None
         try:
-            conn = self.db_pool.getConnection()
+            conn = db.getConnection()
             cur = conn.cursor()
             fields = {'login': self.getLogin(), 'agency': self.getAgency()}
             cur.execute(RESET_USER_PASSWORD_SQL, fields)
             password = cur.fetchone()[0]
             conn.commit()
-            cur.close()
-            self.db_pool.recycleConnection(conn)
-            # Now set and save the passrefresh flag
-            self.needs_passrefresh = True
-            self.store()
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if conn:
-                    self.db_pool.recycleConnection(conn)
-            except:
-                pass
+            db.recycleConnection(conn, cur)
+
+        # Now set and save the passrefresh flag
+        self.needs_passrefresh = True
+        self.store()
+
         return password
 
     def _fetchData(self, id):
-        conn = None
-        cur = None
+        conn, cur = None, None
         try:
-            conn = self.db_pool.getConnection()
+            conn = db.getConnection()
             cur = conn.cursor()
             cur.execute(FETCH_USER_DATA_SQL % id)
             ud = cur.fetchone()
@@ -189,24 +166,18 @@
             self.role = ud[11]
             self._processLoginString()
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if conn:
-                    self.db_pool.recycleConnection(conn)
-            except:
-                pass
+            db.recycleConnection(conn, cur)
     
     def setAdmUser(self):
         lname = "ka_%s_adm" % (getDbName())
+        conn, cur = None, None
         try:
-            conn = self.db_pool.getConnection()
+            conn = db.getConnection()
             cur = conn.cursor()
             fields = {'login': '''%s''' % lname}
-	    cmd = FETCH_USER_SYS_ID_SQL % lname
+            cmd = FETCH_USER_SYS_ID_SQL % lname
             cur.execute(cmd)
             uid = cur.fetchone()[0]
-        
             self.id = 0
             self.first_name = ''
             self.last_name = 'Zentrale Administration'
@@ -217,54 +188,33 @@
             self.role = 'admin_ka'
             self._processLoginString()
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if conn:
-                    self.db_pool.recycleConnection(conn)
-            except:
-                pass
+            db.recycleConnection(conn, cur)
     
 
     def loadByName(self, name):
         # build long loginname as it is stored in the db
         lname = "ka_%s_%s" % (getDbName(), name)
-        conn = None
-        cur = None
+        conn, cur = None, None
         try:
-            conn = self.db_pool.getConnection()
+            conn = db.getConnection()
             cur = conn.cursor()
             fields = {'login': lname}
             cur.execute(FETCH_USER_ID_SQL, fields)
             id = cur.fetchone()
             self._fetchData(id)
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if conn:
-                    self.db_pool.recycleConnection(conn)
-            except:
-                pass
+            db.recycleConnection(conn, cur)
 
     def setStandin(self, uid):
-        con = None
-        cur = None
+        con, cur = None, None
         fields = {'userid': self.id, 'standin':uid}
         try:
-            con = self.db_pool.getConnection()
+            con = db.getConnection()
             cur = con.cursor()
             cur.execute(ALTER_USER_STANDIN_SQL, fields)
             con.commit()
-            cur.close()
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if con:
-                    db_pool.recycleConnection(conn)
-            except:
-                pass
+            db.recycleConnection(con, cur)
 
     def setData(self, data):
         """Eats dictionary holding valid data returned from the formencode validation"""
@@ -277,14 +227,13 @@
         self.needs_passrefresh = data.get('newpass', self.needs_passrefresh) 
 
     def createLogin(self, login=None, role=None, agency=None):
-        conn = None
-        cur = None
         self.login = login
         self.role = role
         self.agency = agency
         password = None
+        conn, cur = None, None
         try:
-            conn = self.db_pool.getConnection()
+            conn = db.getConnection()
             cur = conn.cursor()
             fields = {'loginname': self.login, 
                     'grouprole': self.role, 
@@ -301,34 +250,22 @@
             result = cur.fetchone()
             password = result[0]
             conn.commit()
-            cur.close()
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if conn:
-                    db_pool.recycleConnection(conn)
-            except:
-                pass
+            db.recycleConnection(conn, cur)
         return password
 
     def _init_ka_benutzer(self, username):
         id = None
+        conn, cur = None, None
         try:
-            conn = self.db_pool.getConnection()
+            conn = db.getConnection()
             cur = conn.cursor()
             fields = {'login': username}
             cur.execute(CREATE_USER_SQL_KA, fields)
             id = cur.fetchone()[0]
             conn.commit()
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if conn:
-                    self.db_pool.recycleConnection(conn)
-            except:
-                pass
+            db.recycleConnection(conn, cur)
         return id
 
     def store(self):
@@ -345,22 +282,15 @@
         for key in fields.iterkeys():
             update_str.append('%s=%%(%s)s' % (key, key))
         fields['id'] = self.id
-        conn = None
-        cur = None
+        conn, cur = None, None
         try:
-            conn = self.db_pool.getConnection()
+            conn = db.getConnection()
             cur = conn.cursor()
             sql = STORE_USER_DATA_SQL % ", ".join(update_str)
             cur.execute(sql, fields)
             conn.commit()
         finally:
-            try:
-                if cur:
-                    cur.close()
-                if conn:
-                    self.db_pool.recycleConnection(conn)
-            except:
-                pass
+            db.recycleConnection(conn, cur)
 
     def delete(self):
         pass

Modified: trunk/waskaweb/templates/administration/edit_settings.mako
===================================================================
--- trunk/waskaweb/templates/administration/edit_settings.mako	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/templates/administration/edit_settings.mako	2008-08-13 13:02:47 UTC (rev 8)
@@ -44,7 +44,7 @@
                 % if c.form_errors.get('anon_transfer'):
                   <a href="#error_list"><img class="smallicon" src="/images/error_small.png"></a>
                 % endif
-                % if c.agency.conf.get('anon_transfer') == 'on':
+                % if c.agency.isAnonTransfer():
 
                   <input id="anon_transfer" name="anon_transfer" type="checkbox" checked/>
                 % else:

Modified: trunk/waskaweb/templates/administration/show_settings.mako
===================================================================
--- trunk/waskaweb/templates/administration/show_settings.mako	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/templates/administration/show_settings.mako	2008-08-13 13:02:47 UTC (rev 8)
@@ -23,16 +23,16 @@
 <table>
 <tr>
 <td class="label">${_('adm_form_settings_kaname')}</td>
-  <td>${c.agency.conf.get('ka_name')}</td>
+  <td>${c.agency.getName()}</td>
 </tr>
 <tr>
   <td class="label">${_('adm_form_settings_fkz')}</td>
-  <td>${c.agency.conf.get('fkz')}</td>
+  <td>${c.agency.getFKZ()}</td>
 </tr>
 <tr>
   <td class="label">${_('adm_form_settings_anontransfer')}</td>
   <td>
-    % if c.agency.conf.get('anon_transfer') == 'on':
+    % if c.agency.isAnonTransfer():
       ${_('adm_form_settings_anontransfer_yes')}
     % else:
       ${_('adm_form_settings_anontransfer_no')}

Modified: trunk/waskaweb/templates/documents/case_overview.mako
===================================================================
--- trunk/waskaweb/templates/documents/case_overview.mako	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/templates/documents/case_overview.mako	2008-08-13 13:02:47 UTC (rev 8)
@@ -35,9 +35,9 @@
   %>
   % for f in c.files:
   <tr>
-    <td>${ f.name | F.shorten, h}</td>
+    <td>${ f.getName() | F.shorten, h}</td>
     <td class="number_field">${kb(f.size)} KB</td>
-    <td><a href="/document/caseShow/${f.id}/${f.name | F.H}" target="_blank">Anzeigen</a>
+    <td><a href="/document/caseShow/${f.id}/${f.getName() | F.H}" target="_blank">Anzeigen</a>
     <a href="/document/caseDelete/${f.id}/${myid}/0">Löschen</a>
     </td>
   </tr>

Modified: trunk/waskaweb/templates/documents/global_overview.mako
===================================================================
--- trunk/waskaweb/templates/documents/global_overview.mako	2008-08-13 13:02:24 UTC (rev 7)
+++ trunk/waskaweb/templates/documents/global_overview.mako	2008-08-13 13:02:47 UTC (rev 8)
@@ -33,9 +33,9 @@
   <% kb = lambda x: h.formatNumber(x * 1.0/1024.0) %>
   % for f in c.files:
   <tr>
-    <td>${ f.name | F.shorten, h}</td>
+    <td>${ f.getName() | F.shorten, h}</td>
     <td class="number_field">${kb(f.size)} KB</td>
-    <td><a href="/document/globalShow/${f.id}/${f.name | F.H}" target="_blank">Anzeigen</a>
+    <td><a href="/document/globalShow/${f.id}/${f.getName() | F.H}" target="_blank">Anzeigen</a>
     % if h.hasRole(['admin_ka']):
     <a href="/document/globalDelete/${f.id}">Löschen</a>
     % endif



More information about the Mpuls-commits mailing list