[Zope-DB] Re: Database connection in a file system product

Bob Corriher bobc at p-wave.com
Thu Apr 27 12:39:34 EDT 2006


Hi Jonas,

Here is some code I use to create a DA during product installation:

from Products.mxODBCZopeDA.ZopeDA import ZopeConnection

    security.declarePrivate('manage_afterAdd')
    def manage_afterAdd(self, item, container):
        # add mxODBC connection

        conn_string = readDatabaseConfig()
        tmpConnection = ZopeConnection('dbConnection',
                        'Database Connection',
                        conn_string,
                        connection_check=True
                        )

        self._setObject('dbConnection', tmpConnection)


 It is in the manage_afterAdd method of my product, which basically 
creates a site object to hang the rest of my code and skins on. In this 
case it's creating an mxODBCDA connection, but the same principle would 
apply for any DA. I think for most other DA's the "ZopeConnection" 
method will be "Connection".

It uses a config file (using ZConfig) which looks like this to set the 
conn_string. The conn_string will vary somewhat depending on the DA. A 
typical config file looks like this:

dsn       development
user      master
password  xxxxxxxx

and a ZConfig schema:

<schema prefix="DatabaseConfig.database">

<key name="dsn"      datatype="string" required="yes"/>
<key name="user"     datatype="string" required="yes"/>
<key name="password" datatype="string" required="yes"/>

</schema>


The readDatabaseConfig module is:

import ZConfig
import os
from Globals import package_home

def readDatabaseConfig(newlines=True):
    SCHEMA = os.path.join(package_home(globals()), 'schema_odbc.xml')
    config_file = os.path.join(package_home(globals()), 
'database_odbc.conf')
   
    schema = ZConfig.loadSchema(SCHEMA)
    cfg, nil = ZConfig.loadConfig(schema, config_file)

    if newlines:
        nl = '\n'
    else:
        nl = ''
    return 'DSN=%s;%sUID=%s;%sPWD=%s' \
           % (cfg.dsn, nl, cfg.user, nl, cfg.password)

I use this because we set up many separate sites all using this product 
and it saves the manual installation and also standardizes naming 
conventions (all the DA's get the same id: dbConnection). I also 
sometimes have sysadmins not familiar with Zope doing installs for me.

You should be able to modify this for your DA.

HTH

Bob Corriher
CTO
P-Wave Inc.


More information about the Zope-DB mailing list