I must be an idiot, please pity me!
bdesth at nospam.free.fr
Thu Sep 12 06:25:59 CEST 2002
> 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:
> 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
> 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!
Creating a db connection in each function for sure not be very
efficient.But what's wrong with passing the database connection to the
functions in mod1, mod2, and modXXX ???
Anyway, you can make it simpler, like this :
in each module,
- create a global db_connection variable
- add an init() function, that takes a db_connection as argument and
assign it to the module's global db_connection variable
- and don't forget to call this function before any other.
Another, more OO way to do this would be to rewrite your modules as
classes, each getting a db_connection argument in it's __init__(), and
then, in the main script, create the needed objects.
This second solution is somewhat safer with threading (if each thread
creates it's own connection and it's own objects...)
More information about the Python-list