Multiple modules with database access + general app design?
rob at digital-crocus.com
Thu Jan 19 16:05:51 CET 2006
On Thu, 19 Jan 2006 06:38:39 -0800, Frank Millman wrote:
> Robin Haswell wrote:
>> 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()
>> 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.
> This is what I do.
> Create a separate module to contain your global variables - mine is
> called 'common'.
> In common, create a class, with attributes, but with no methods. Each
> attribute becomes a global variable. My class is called 'c'.
> At the top of every other module, put 'from common import c'.
> Within each module, you can now refer to any global variable as
> You can create class attributes on the fly. You can therefore have
> something like -
> c.db = MySql.connect(...)
> All modules will be able to access c.db
> As Daniel has indicated, it may not be safe to share one connection
> across multiple threads, unless you can guarantee that one thread
> completes its processing before another one attempts to access the
> database. You can use threading locks to assist with this.
> Frank Millman
Thanks, that sounds like an excellent idea. While I don't think it applies
to the database (threading seems to be becoming a bit of an issue at the
moment), I know I can use that in other areas :-)
More information about the Python-list