| Danilo Fiorenzano 
    danilo at telusplanet.net Sun May 28 18:54:02 EST 2000 
 On Sun, 28 May 2000, Cary O'Brien wrote:
 
> 1) How are people handling persistant database connections?
> [....]
>    It seems from the documentation that each request gets its own
>    subinterpreter.
Since global vars retain their values between requests serviced by the
same httpd process, I ended up doing something like this:
---------------- cut ---------------- cut ---------------- cut ----------------
import informixdb
import os, re, cgi, string
from mod_python import apache
_dbconn = None
def handler(req):
    global _dbconn
    ... etc etc ...
    results = findProducts('acid')
    ... etc etc ...
def findProducts(substring):
    global _dbconn
    if _dbconn == None:
        try:
            _dbconn = informixdb.informixdb('db at server', 'user', 'password')
        except:
            return ['Access Denied']
    c = _dbconn.cursor()
    blah = "%" + string.lower(substring) + "%"
    c.execute("select strshippingname from tblproducts where lower(strshippingname) like ?", (blah,))
    retval = []
    for row in c.fetchall():
        retval.append(row[0])
    return retval
---------------- cut ---------------- cut ---------------- cut ----------------
  This works exactly as you want, although it should also have a "try:
except:" block around the actual query, to recover from dropped
connections et similia.  Otherwise, normally the connection is
established only when a freshly-spawned httpd executes a query for the
first time, and should persist until it reaches 'MaxRequestsPerChild"
in httpd.conf - then the httpd instance is terminated and the
connection is closed automatically.
 I have been wondering how one could automatically preload a Python
module upon start of a new httpd, so users would not have to endure
the occasional delay due to the opening of a new connection to the
database.  I suspect it may be possible by using some apache
directives, but I haven't really looked into it yet :)
-- Shade
 |