[mod_python] How to make mod_python know when Apache is shutdown/restarted?

Graham Dumpleton grahamd at dscpl.com.au
Fri Aug 5 18:39:13 EDT 2005

On 06/08/2005, at 7:52 AM, Scott Chapman wrote:

> Scott Chapman wrote:
>> I need to make mod_python close the database connection nicely when 
>> Apache is shutdown or restarted.  How do I get this info into 
>> mod_python's world?
> I found the Server's "register cleanup(request, callable[, data ])" 
> method.
> When do I call it?
> It seems it should be done once per Apache child process, not with 
> every request.

Since to get the server object you need a request object, the only
option is to call it as a side effect of a request. To avoid calling it
more than once, you simply need to keep a global data flag some where
which you can set the first time you register the cleanup handler
thereby avoiding calling it again. If using a multithreaded MPM, just
make sure you thread protect access to the flag and registration of the
cleanup handler so you don't get race conditions.

Note that the consequence of this is you can't really create a database
connection using PythonImport but have to wait until the first time it
is required by any request. If you did do it from PythonImport, and
Apache was shutdown before a request was handled that needed the
database connection, you wouldn't get your cleanup handler called as it
wouldn't have been registered yet.

> I don't see a way to run something only when mod_python is 
> instantiated initially.

Correct, see:


I still believe it would be possible to implement such a feature, and
previously described how I felt it could be done, but it has low
priority in the scheme of things.


More information about the Mod_python mailing list