6.3 CGI Handler

 

CGI handler is a handler that emulates the CGI environment under mod_python.

Note that this is not a "true" CGI environment in that it is emulated at the Python level. stdin and stdout are provided by substituting sys.stdin and sys.stdout, and the environment is replaced by a dictionary. The implication is that any outside programs called from within this environment via os.system, etc. will not see the environment available to the Python program, nor will they be able to read/write from standard input/output with the results expected in a "true" CGI environment.

The handler is provided as a stepping stone for the migration of legacy code away from CGI. It is not recommended that you settle on using this handler as the preferred way to use mod_python for the long term. This is because the CGI environment was not intended for execution within threads (e.g. requires changing of current directory with is inherently not thread-safe, so to overcome this cgihandler maintains a thread lock which forces it to process one request at a time in a multi-threaded server) and therefore can only be implemented in a way that defeats many of the advantages of using mod_python in the first place.

To use it, simply add this to your .htaccess file:

  SetHandler mod_python
  PythonHandler mod_python.cgihandler

As of version 2.7, the cgihandler will properly reload even indirectly imported module. This is done by saving a list of loaded modules (sys.modules) prior to executing a CGI script, and then comparing it with a list of imported modules after the CGI script is done. Modules (except for whose whose __file__ attribute points to the standard Python library location) will be deleted from sys.modules thereby forcing Python to load them again next time the CGI script imports them.

If you do not want the above behavior, edit the cgihandler.py file and comment out the code delimited by ###.

Tests show the cgihandler leaking some memory when processing a lot of file uploads. It is still not clear what causes this. The way to work around this is to set the Apache MaxRequestsPerChild to a non-zero value.