[mod_python] database connection

Julien Cigar jcigar at ulb.ac.be
Sat Oct 15 14:28:10 EDT 2005


Hello,

I use mod_python for some time now, and I wondered where's the best 
place to manage database connections / cursors ?
I run a home made 'publisher' handler and what I'm actually doing is to 
open a global database connection in the index.py, and pass this 
variable in classes ... is this the best way ?

a little example:

-> index.py:

import psycopg
from mod_python import apache

config = apache.import_module('config')
connection = psycopg.connect(config.getDbConnectionString())

def action1 (req):
 pageAction1 = apache.import_module('pages/action1')
 page = pageAction1.pageAction1(connection)
 return __render (req, 'action1')

def action2 (req):
 name = req.form.getfirst('name')
 pageAction2 = apache.import_module('pages/action2')
 page = pageAction2.pageAction2(connection, name)
 return __render (req, 'action2')

....

-> pages/action1.py:

class pageAction1:
 def __init__(self, conn):
   self.connection = conn
   self.cursor = conn.cursor()

 def getList(self, foo, bar):
   blah = self.cursor.execute('SELECT * FROM bleh')
   return self.cursor.dictfetchall()

...

(truncated for visibility ...)

Thanks


More information about the Mod_python mailing list