[Mpuls-commits] r5996 - base/trunk/mpulsweb/lib

scm-commit at wald.intevation.org scm-commit at wald.intevation.org
Tue Jun 26 11:40:14 CEST 2012


Author: bricks
Date: 2012-06-26 11:40:14 +0200 (Tue, 26 Jun 2012)
New Revision: 5996

Modified:
   base/trunk/mpulsweb/lib/db.py
Log:
Add a DB cursor method

The db cursor method can be used in a context manager without
creating a transaction. Also convert DB to an new style class.


Modified: base/trunk/mpulsweb/lib/db.py
===================================================================
--- base/trunk/mpulsweb/lib/db.py	2012-06-26 09:38:27 UTC (rev 5995)
+++ base/trunk/mpulsweb/lib/db.py	2012-06-26 09:40:14 UTC (rev 5996)
@@ -78,7 +78,7 @@
     return "'" + s.replace("\\", "\\\\").replace("'", "\\'") + "'"
 
 
-class DB:
+class DB(object):
 
     def __init__(self, database, user, password, host='localhost', port=5432):
         self.database = database
@@ -161,6 +161,24 @@
                 con.rollback()
             self.recycleConnection(con, cur)
 
+    @contextmanager
+    def cursor(self):
+        """Return a context manager for performing queries on a cursor
+        Example usage:
+            with db.cursor() as cur:
+                cur.execute("SELECT bar FROM ...")
+                ...
+
+        The context manager will automatically recycle the received connection.
+        """
+        cur = None
+        con = self.getConnection()
+        try:
+            cur = con.cursor()
+            yield cur
+        finally:
+            self.recycleConnection(con, cur)
+
     def execute(self, statement, *args):
         """Execute an SQL statement in a transaction.
 



More information about the Mpuls-commits mailing list