Multiple modules with database access + general app design?

Frank Millman frank at chagford.com
Thu Jan 19 09:38:39 EST 2006


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()
> 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.
>

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
c.whatever.

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.

HTH

Frank Millman




More information about the Python-list mailing list