I must be an idiot, please pity me!
Greg Fortune
lists at gregfortune.com
Thu Sep 12 00:10:50 EDT 2002
Sure, make another module named db. Provide a couple functions in db like
connect and query.
Then in CGI1.py
import db
import mod1
import mod2
db.connect(host, db_name, user, pass)
#do your stuff
And in mod1
import db
def functiona():
return db.query('SELECT * FROM some_table')
The db module would need to look something like this
#assuming you are using MySQL
import MySQLdb
THE_CURSOR = None
def connect(host, db_name, user, pass):
global THE_CURSOR
the_db = MySQL.connect(user=user, passwd=pass, db=db_name,
hostname=host)
THE_CURSOR = the_db.cursor()
def query(query_string):
return THE_CURSOR.execute(query_string)
Of course, that doesn't take into account connecting to multiple database,
connections sharing, closing the connection, etc... But it should work for
what you're trying to do. If you'd like a more powerful db module, let me
know and I can share some of the code I've developed over the past couple
years.
Greg Fortune
Fortune Solutions
newbie wrote:
> Hello all. I'm getting very desperate now, so I have to ask for some help.
> I'm working on a small project and have slipped into what must be
> namespace hell.
>
> I have a few controlling CGI scripts that use functions from other modules
> to build parts of a page. Each function in these other modules contains
> the SQL processing and HTML building code grouped by related data. The
> idea being I can reuse the functions in the other scripts. All works fine,
> providing each modules connects to the database as a stand alone job, or I
> pass a database connection object thing to each and every function. I
> suspect that both of these are wrong, due to the ugliness or nasty system
> overhead of the datbase connections.
>
> What I thought I should be able to do is:
>
> CGI1.py:
>
> import mod1, mod2
>
> connect to database
>
> create part of page using mod1.functiona
> create part of page using mod1.functionb
> create part of page using mod2.functionz
>
> close database
>
>
> But it doesn't seem to work like that. I've trawled though google and deja
> for days (plus a couple of new rider books), and no one seems to hit this
> problem. I must have a HUGE misunderstanding somewhere. I know mod1 and
> mod2 cannot see CGI.py namespace, but there must be a way of sharing the
> database connection, mustn't there?
>
> Help or a kick up the bottom would be really appreciated here!
>
> Sammy.
More information about the Python-list
mailing list