Multiple modules with database access + general app design?

Robin Haswell rob at digital-crocus.com
Thu Jan 19 11:28:37 CET 2006


Hey people

I'm an experience PHP programmer who's been writing python for a couple of
weeks now. I'm writing quite a large application which I've decided to
break down in to lots of modules (replacement for PHP's include()
statement).

My problem is, in PHP if you open a database connection it's always in
scope for the duration of the script. Even if you use an abstraction layer
($db = DB::connect(...)) you can `global $db` and bring it in to scope,
but in Python I'm having trouble keeping the the database in scope. At the
moment I'm having to "push" the database into the module, but I'd prefer
the module to bring the database connection in ("pull") from its parent.

Eg:
	import modules
	modules.foo.c = db.cursor()
	modules.foo.Bar()

Can anyone recommend any "cleaner" solutions to all of this? As far as I
can see it, Python doesn't have much support for breaking down large
programs in to organisable files and referencing each other.

Another problem is I keep having to import modules all over the place. A
real example is, I have a module "webhosting", a module "users", and a
module "common". These are all submodules of the module "modules" (bad
naming I know). The database connection is instantiated on the "db"
variable of my main module, which is "yellowfish" (a global module), so
get the situation where:

	(yellowfish.py)
	import modules
	modules.webhosting.c = db.cursor()
	modules.webhosting.Something()

webhosting needs methods in common and users:

	from modules import common, users

However users also needs common:

	from modules import common

And they all need access to the database

	(users and common)
	from yellowfish import db
	c = db.cursor()

Can anyone give me advice on making this all a bit more transparent? I
guess I really would like a method to bring all these files in to the same
scope to make everything seem to be all one application, even though
everything is broken up in to different files.

One added complication in this particular application:

I used modules because I'm calling arbitrary methods defined in some XML
format. Obviously I wanted to keep security in mind, so my application
goes something like this:

	import modules
	module, method, args = getXmlAction()
	m = getattr(modules, module)
	m.c = db.cursor()
	f = getattr(m, method)
	f(args)

In PHP this method is excellent, because I can include all the files I
need, each containing a class, and I can use variable variables:

	<?php
	$class = new $module;	// can't remember if this works, there are
				// alternatves though
	$class->$method($args);
	?>

And $class->$method() just does "global $db; $db->query(...);".

Any advice would be greatly appreciated!

Cheers

-Robin Haswell



More information about the Python-list mailing list