[mod_python] 2006 "MySQL server has gone away" failures

Jorey Bump list at joreybump.com
Fri Jan 12 12:31:26 EST 2007


Martijn Moeling wrote:

> First you should create a database connection non globally the best way
> to do so is to create it as part of the req object in your handler
> 
> I suggest you do in your handler routine:
> 
> def handler(req):
> 	req.database=whatever to connect to your database
> 	req.cursor=req.database.cursor()
> 	req.register_cleanup(closedb,req)	
> 	... # dor the rest of your stuff
> 
> Note the register cleanup line, this is always called, even  if the
> request fails with a python error:
> 
> def closedb(req):
> 	req.cursor.close()
> 	req.database.close()
> 	
> Now the connections get closed nicely and mysql does not run out of
> resources anymore.

Interesting solution, but aren't you now (briefly) opening a database 
connection for every page view, regardless of it actually needing one?

Also, it looks like the OP is using the PSP handler, not a custom one. 
In that case, the best solution might be to explicitly open and close 
the db handle before and after every query (or tightly grouped series of 
queries). Recent versions of MySQLdb have made it difficult to create 
persistent db connections, and users are advised against it, since the 
overhead of creating new connections is negligible. I had to rewrite a 
number of applications that imported a shared db handle, due to this 
change. Bummer. :(




More information about the Mod_python mailing list