[mod_python] how to use Mysql on mod_python+apache?

Mike Looijmans nlv11281 at natlab.research.philips.com
Fri Mar 30 01:55:57 EST 2007

 > ...
> with this method of using mysqldb, the database connection is closed
> properly, even if the handler code runs into an error, if not and an
> error occurs and the connection is kept by MySQL and at the end it will
> run out of resources (and/or memory whatever comes first).

I did notice in the past that when a MySQLdb connection object goes out of scope, it was not 
immediately closed(), so there are probably cyclic dependencies inside. However, the garbage 
collector should pick them up soon enough.

In the past, i have often created something alike a publisher handler, but which allowed the 
callables to accept a "db" parameter. This would trigger the handler to setup a DB connection, and 
using a try..finally... block assured that the connection was being closed (or recycled to the pool) 
asap. Using a connection pool (to prevent re-connect time) turned out to be simple but useless on 
MySQL, I could not measure (and statistically prove) a performance improvement.

Another good tip:
If the MySQL database is running on the same host as the webserver, you can probably disable TCP/IP 
completely for the database server. The MySQLdb interface is using slightly more efficient UNIX 
sockets (or named pipes if on Windows) anyway for local connections, and disabling network 
connections greatly improves security, since you can only make connections from localhost. Putting 
the mysql username/password in a plaintext file is no problem then. I usually use SSH to manage the 
database remotely.

More information about the Mod_python mailing list