[mod_python] avoiding database connection leak on module (re)import

Mateusz Korniak mateusz at ant.gliwice.pl
Mon Dec 4 06:51:28 EST 2006


On Monday 04 December 2006 12:03, Clodoaldo wrote:
> 2006/12/4, Mark Harrison <mh at pixar.com>:
> > Whenever the source file is modified, mod_python re-imports the
> > file.  A naive program will have a connection leak if it just
> > has a line like this:
> >
> > myconnection = mydbpackage.connect(...)

If module variable space is no longer accessible,  myconnection ref count 
should fall to zero( unless you keep reference to it somewhere else), so 
myconnection will be deleted and in non-buggy module should also 
close "physical" connection to DB (or put it in available connections pool) .

> > So, I'm closing and reopening the connection on each re-import:
> >
> > try:
> >      myconnection.close()

Don't you always get NameError: name 'myconnection' is not defined there ?

> > except NameError:
> >      pass
> > myconnection = mydbpackage.connect(...)
> >
> > Is there a better, more  mod_pythonic way to handle this type of
> > situation?
>
> Good question. I think I'm doing it right since there are no more
> connections than apache processes, but I'm not sure how exactly it
> works.

Pythonic way in simplest case is to simple get DB connection and keep only 
necessary references to it.

>
> In the virtual server config:
>
>     PythonImport _db_connection carconsumption.com
>
> The _db_connection module:
>
> from psycopg2.pool import PersistentConnectionPool as _PCP
> _pcp = _PCP(1, 1, "host=localhost dbname=carconsumption user=user
> password=password")
> _connection = _pcp.getconn()
>
> When I need the connection:
>
> from _db_connection import _connection
> ...
> cursor = _connection.cursor()
> cursor.execute(query, d)
> ...
> cursor.close()
>
> I never close the connection.

-- 
Mateusz Korniak


More information about the Mod_python mailing list