
\chapter{Python API\label{pythonapi}}

\section{Multiple Interpreters\label{pyapi-interps}}
      
When working with mod_python, it is important to be aware of a feature
of Python that is normally not used when using the language for
writing scripts to be run from command line. This feature is not
available from within Python itself and can only be accessed through
the \citetitle[http://www.python.org/doc/current/api/api.html]{C
language API}.

Python C API provides the ability to create \dfn{subinterpreters}. A
more detailed description of a subinterpreter is given in the
documentation for the
\citetitle[http://www.python.org/doc/current/api/initialization.html]{\cfunction{Py_NewInterpreter()}}
function. For this discussion, it will suffice to say that each
subinterpreter has its own separate namespace, not accessible from
other subinterpreters. Subinterpreters are very useful to make sure
that separate programs running under the same Apache server do not
interfere with one another.

At server start-up or mod_python initialization time, mod_python
initializes an interpreter called \dfn{main} interpreter.  The main
interpreter contains a dictionary of subinterpreters. Initially, this
dictionary is empty. With every request, as needed, subinterpreters
are created, and references to them are stored in this dictionary. The
dictionary is keyed on a string, also known as \emph{interpreter
name}. This name can be any string.  The main interpreter is named
\samp{main_interpreter}.  The way all other interpreters are named can
be controlled by \code{PythonInterp*} directives. Default behaviour is
to name interpreters using the Apache virtual server name
(\code{ServerName} directive). This means that all scripts in the same
virtual server execute in the same subinterpreter, but scripts in
different virtual servers execute in different subinterpreters with
completely separate namespaces.
\citetitle[dir-other-ipd.html]{\code{PythonInterpPerDirectory}} and
\citetitle[dir-other-ipdv.html]{\code{PythonInterpPerDirective}}
directives alter the naming convention to use the absolute path of the
directory being accessed, or the directory in which the
\code{Python*Handler} was encountered, respectively.
\citetitle[dir-other-pi.html]{\code{PythonInterpreter}} can be used to
force the interpreter name to a specific string overriding any naming
conventions.

Once created, a subinterpreter will be reused for subsequent requests.
It is never destroyed and exists until the Apache process dies.

You can find out the name of the interpreter under which you're
running by peeking at \member{req.interpreter}.

\begin{seealso}
  \seetitle[http://www.python.org/doc/current/api/api.html]
           {Python C Language API}{Python C Language API}
\end{seealso}

\section{Overview of a Request Handler\label{pyapi-handler}}
\indexii{request}{handler}

A \dfn{handler} is a function that processes a particular phase of a
request. Apache processes requests in phases - read the request,
process headers, provide content, etc. For every phase, it will call
handlers, provided by either the Apache core or one of its modules,
such as mod_python which passes control to functions provided by the
user and written in Python. A handler written in Python is not any
different from a handler written in C, and follows these rules:

\index{req} \indexii{request}{object} A handler function will always
be passed a reference to a request object. (Throughout this manual,
the request object is often referred to by the \code{req} variable.)

Every handler can return:

\begin{itemize}

\item
  \constant{apache.OK}, meaning this phase of the request was handled by this 
  handler and no errors occurred. 

\item
  \constant{apache.DECLINED}, meaning this handler has not handled this
  phase of the request to completion and Apache needs to look for
  another handler in subsequent modules.
  
\item
  \constant{apache.\emph{HTTP_ERROR}}, meaning an HTTP error occurred. 
  \var{HTTP_ERROR} can be any of the following:

  \begin{verbatim}
    HTTP_CONTINUE                     = 100
    HTTP_SWITCHING_PROTOCOLS          = 101
    HTTP_PROCESSING                   = 102
    HTTP_OK                           = 200
    HTTP_CREATED                      = 201
    HTTP_ACCEPTED                     = 202
    HTTP_NON_AUTHORITATIVE            = 203
    HTTP_NO_CONTENT                   = 204
    HTTP_RESET_CONTENT                = 205
    HTTP_PARTIAL_CONTENT              = 206
    HTTP_MULTI_STATUS                 = 207
    HTTP_MULTIPLE_CHOICES             = 300
    HTTP_MOVED_PERMANENTLY            = 301
    HTTP_MOVED_TEMPORARILY            = 302
    HTTP_SEE_OTHER                    = 303
    HTTP_NOT_MODIFIED                 = 304
    HTTP_USE_PROXY                    = 305
    HTTP_TEMPORARY_REDIRECT           = 307
    HTTP_BAD_REQUEST                  = 400
    HTTP_UNAUTHORIZED                 = 401
    HTTP_PAYMENT_REQUIRED             = 402
    HTTP_FORBIDDEN                    = 403
    HTTP_NOT_FOUND                    = 404
    HTTP_METHOD_NOT_ALLOWED           = 405
    HTTP_NOT_ACCEPTABLE               = 406
    HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
    HTTP_REQUEST_TIME_OUT             = 408
    HTTP_CONFLICT                     = 409
    HTTP_GONE                         = 410
    HTTP_LENGTH_REQUIRED              = 411
    HTTP_PRECONDITION_FAILED          = 412
    HTTP_REQUEST_ENTITY_TOO_LARGE     = 413
    HTTP_REQUEST_URI_TOO_LARGE        = 414
    HTTP_UNSUPPORTED_MEDIA_TYPE       = 415
    HTTP_RANGE_NOT_SATISFIABLE        = 416
    HTTP_EXPECTATION_FAILED           = 417
    HTTP_UNPROCESSABLE_ENTITY         = 422
    HTTP_LOCKED                       = 423
    HTTP_FAILED_DEPENDENCY            = 424
    HTTP_INTERNAL_SERVER_ERROR        = 500
    HTTP_NOT_IMPLEMENTED              = 501
    HTTP_BAD_GATEWAY                  = 502
    HTTP_SERVICE_UNAVAILABLE          = 503
    HTTP_GATEWAY_TIME_OUT             = 504
    HTTP_VERSION_NOT_SUPPORTED        = 505
    HTTP_VARIANT_ALSO_VARIES          = 506
    HTTP_INSUFFICIENT_STORAGE         = 507
    HTTP_NOT_EXTENDED                 = 510
  \end{verbatim}                      

\end{itemize}

As an alternative to \emph{returning} an HTTP error code, handlers can
signal an error by \emph{raising} the \constant{apache.SERVER_RETURN}
exception, and providing an HTTP error code as the exception value,
e.g.

\begin{verbatim}
raise apache.SERVER_RETURN, apache.HTTP_FORBIDDEN
\end{verbatim}

Handlers can send content to the client using the \method{req.write()}
method. 

Client data, such as POST requests, can be read by using the
\method{req.read()} function.

\begin{notice}
  The directory of the Apache \code{Python*Handler} 
  directive in effect is prepended to the \code{sys.path}. If the
  directive was specified in a server config file outside any
  \code{<Directory>}, then the directory is unknown and not prepended.
\end{notice}

An example of a minimalistic handler might be: 

\begin{verbatim}
from mod_python import apache

def requesthandler(req):
    req.content_type = "text/plain"
    req.write("Hello World!")
    return apache.OK
\end{verbatim}

\section{Overview of a Filter Handler\label{pyapi-filter}}
\indexii{filter}{handler}

A \dfn{filter handler} is a function that can alter the input or the
output of the server. There are two kinds of filters - \dfn{input} and
\dfn{output} that apply to input from the client and output to the
client respectively.

At this time mod_python supports only request-level filters, meaning
that only the body of HTTP request or response can be filtered. Apache
provides support for connection-level filters, which will be supported
in the future.

A filter handler receives a \emph{filter} object as its argument. The
request object is available as well via \code{filter.req}, but all
writing and reading should be done via the filter's object read and
write methods.

Filters need to be closed when a read operation returns None 
(indicating End-Of-Stream).

The return value of a filter is ignored. Filters cannot decline
processing like handlers, but the same effect can be achieved
by using the \method{filter.pass_on()} method.

Filters must first be registered using \code{PythonInputFilter} or
\code{PythonOutputFilter}, then added using the Apache
\code{Add/SetInputFilter} or \code{Add/SetOutputFilter} directives. 

Here is an example of how to specify an output filter, it tells the
server that all .py files should processed by CAPITALIZE filter:

\begin{verbatim}
  PythonOutputFilter capitalize CAPITALIZE
  AddOutputFilter CAPITALIZE .py
\end{verbatim}

And here is what the code for the \file{capitalize.py} might look
like:

\begin{verbatim}
from mod_python import apache
  
def outputfilter(filter):

    s = filter.read()
    while s:
        filter.write(s.upper())
        s = filter.read()

    if s is None:
        filter.close()

\end{verbatim}

When writing filters, keep in mind that a filter will be called any
time anything upstream requests an IO operation, and the filter has no
control over the amount of data passed through it and no notion of
where in the request processing it is called. For example, within a
single request, a filter may be called once or five times, and there
is no way for the filter to know beforehand that the request is over
and which of calls is last or first for this request, thought
encounter of an EOS (None returned from a read operation) is a fairly
strong indication of an end of a request.

Also note that filters may end up being called recursively in
subrequests. To avoid the data being altered more than once, always
make sure you are not in a subrequest by examining the \code{req.main}
value.

For more information on filters, see
\citetitle[http://httpd.apache.org/docs-2.0/developer/filters.html]{http://httpd.apache.org/docs-2.0/developer/filters.html}.

\section{Overview of a Connection Handler\label{pyapi-conn}}
\indexii{connection}{handler}

A \dfn{connection handler} handles the connection, starting almost
immediately from the point the TCP connection to the server was
made. 

Unlike HTTP handlers, connection handlers receive a \emph{connection}
object as an argument.

Connection handlers can be used to implement protocols. Here is an
example of a simple echo server:

Apache configuration:
\begin{verbatim}
  PythonConnectionHandler echo
\end{verbatim}

Contents of \filenq{echo.py} file:

\begin{verbatim}
from mod_python import apache

def connectionhandler(conn):

    while 1:
        conn.write(conn.readline())

    return apache.OK
\end{verbatim}

\section{\module{apache} -- Access to Apache Internals.}
\declaremodule[apache]{extension}{apache}
\modulesynopsis{Access to Apache Internals}
\moduleauthor{Gregory Trubetskoy}{grisha@apache.org}

The Python interface to Apache internals is contained in a module
appropriately named \module{apache}, located inside the
\module{mod_python} package. This module provides some important
objects that map to Apache internal structures, as well as some useful
functions, all documented below. (The request object also provides an
interface to Apache internals, it is covered in its own section of
this manual.)

\indexii{_apache}{module} The \module{apache} module can only be
imported by a script running under mod_python. This is because it
depends on a built-in module \module{_apache} provided by
mod_python.

It is best imported like this:

\begin{verbatim}
from mod_python import apache
\end{verbatim}

\module{mod_python.apache} module defines the following functions and
objects. For a more in-depth look at Apache internals, see the
\citetitle[http://httpd.apache.org/dev/]{Apache Developer page}

\subsection{Functions\label{pyapi-apmeth}}

\begin{funcdesc}{log_error}{message\optional{, level, server}}
  An interface to the Apache \code{ap_log_error()}
  function. \var{message} is a string with the error message,
  \var{level} is one of the following flags constants:

  \begin{verbatim}
    APLOG_EMERG
    APLOG_ALERT
    APLOG_CRIT
    APLOG_ERR
    APLOG_WARNING
    APLOG_NOTICE
    APLOG_INFO
    APLOG_DEBUG
    APLOG_NOERRNO
  \end{verbatim}            
  
  \var{server} is a reference to a \member{req.server} object. If
  \var{server} is not specified, then the error will be logged to the
  default error log, otherwise it will be written to the error log for
  the appropriate virtual server. When \var{server} is not specified,
  the setting of LogLevel does not apply, the LogLevel is dictated by
  an httpd compile-time default, usually \code{warn}.

  If you have a reference to a request object available, consider using
  \method{req.log_error} instead, it will prepend request-specific
  information such as the source IP of the request to the log entry.
\end{funcdesc}

\begin{funcdesc}{import_module}{module_name\optional{, autoreload=1, log=0, path=None}}
  This function can be used to import modules taking advantage of
  mod_python's internal mechanism which reloads modules automatically
  if they have changed since last import. 

  \var{module_name} is a string containing the module name (it can
  contain dots, e.g. \code{mypackage.mymodule}); \var{autoreload}
  indicates whether the module should be reloaded if it has changed since
  last import; when \var{log} is true, a message will be written to
  the logs when a module is reloaded; \var{path} allows restricting
  modules to specific paths.

  Example:

  \begin{verbatim}
    from mod_python import apache
    mymodule = apache.import_module('mymodule', log=1)
  \end{verbatim}
\end{funcdesc}

\begin{funcdesc}{allow_methods}{\optional{*args}}
  A convenience function to set values in \member{req.allowed}.
  \member{req.allowed} is a bitmask that is used to construct the
  \samp{Allow:} header. It should be set before returning a
  \code{HTTP_NOT_IMPLEMENTED} error.

  Arguments can be one or more of the following:
  \begin{verbatim}
    M_GET
    M_PUT
    M_POST
    M_DELETE
    M_CONNECT
    M_OPTIONS
    M_TRACE
    M_PATCH
    M_PROPFIND
    M_PROPPATCH
    M_MKCOL
    M_COPY
    M_MOVE
    M_LOCK
    M_UNLOCK
    M_VERSION_CONTROL
    M_CHECKOUT
    M_UNCHECKOUT
    M_CHECKIN
    M_UPDATE
    M_LABEL
    M_REPORT
    M_MKWORKSPACE
    M_MKACTIVITY
    M_BASELINE_CONTROL
    M_MERGE
    M_INVALID
  \end{verbatim}

\end{funcdesc}

\begin{funcdesc}{exists_config_define}{name}
    This function returns True if the Apache server was launched
    with the definition with the given \var{name}. This means
    that you can test whether Apache was launched with the \code{-DFOOBAR}
    parameter by calling \code{apache.exists_config_define('FOOBAR')}.
\end{funcdesc}

\begin{methoddesc}[server]{register_cleanup}{handler\optional{, data}}
  Registers a cleanup. Equivalent to \function{req.register_cleanup()}
  or \function{req.server.register_cleanup()}, except that a server or request
  object is not required.
\end{methoddesc}

\begin{funcdesc}{config_tree}{}
  Returns the server-level configuration tree. This tree does not
  include directives from .htaccess files. This is a \emph{copy} of
  the tree, modifying it has no effect on the actual configuration.
\end{funcdesc}

\begin{funcdesc}{server_root}{}
  Returns the value of ServerRoot.
\end{funcdesc}

\begin{funcdesc}{make_table}{} 
  This function is obsolete and is an alias to \class{table} (see below).
\end{funcdesc}

\begin{funcdesc}{mpm_query}{code}
  Allows querying of the MPM for various parameters such as numbers of
  processes and threads. The return value is one of three constants:
  \begin{verbatim}
AP_MPMQ_NOT_SUPPORTED      = 0  # This value specifies whether 
                                # an MPM is capable of         
                                # threading or forking.        
AP_MPMQ_STATIC             = 1  # This value specifies whether 
                                # an MPM is using a static # of
                                # threads or daemons.          
AP_MPMQ_DYNAMIC            = 2  # This value specifies whether 
                                # an MPM is using a dynamic # of
                                # threads or daemons.          
  \end{verbatim}

  The \var{code} argument must be one of the following:
  \begin{verbatim}
AP_MPMQ_MAX_DAEMON_USED    = 1  # Max # of daemons used so far 
AP_MPMQ_IS_THREADED        = 2  # MPM can do threading         
AP_MPMQ_IS_FORKED          = 3  # MPM can do forking           
AP_MPMQ_HARD_LIMIT_DAEMONS = 4  # The compiled max # daemons   
AP_MPMQ_HARD_LIMIT_THREADS = 5  # The compiled max # threads   
AP_MPMQ_MAX_THREADS        = 6  # # of threads/child by config 
AP_MPMQ_MIN_SPARE_DAEMONS  = 7  # Min # of spare daemons       
AP_MPMQ_MIN_SPARE_THREADS  = 8  # Min # of spare threads       
AP_MPMQ_MAX_SPARE_DAEMONS  = 9  # Max # of spare daemons       
AP_MPMQ_MAX_SPARE_THREADS  = 10 # Max # of spare threads       
AP_MPMQ_MAX_REQUESTS_DAEMON= 11 # Max # of requests per daemon 
AP_MPMQ_MAX_DAEMONS        = 12 # Max # of daemons by config   
  \end{verbatim}

Example:
  \begin{verbatim}
if apache.mpm_query(apache.AP_MPMQ_IS_THREADED):
    # do something
else:
    # do something else
  \end{verbatim}
\end{funcdesc}

\subsection{Table Object (mp_table)\obindex{table}\label{pyapi-mptable}}

\index{table}
\begin{classdesc}{table}{\optional{mapping-or-sequence}}
  Returns a new empty object of type \code{mp_table}. See Section
  \ref{pyapi-mptable} for description of the table object. The
  \var{mapping-or-sequence} will be used to provide initial values for
  the table.  

  The table object is a wrapper around the Apache APR table. The table
  object behaves very much like a dictionary (including the Python 2.2
  features such as support of the \code{in} operator, etc.), with the 
  following differences:

  \begin{itemize}
  \item
    Both keys and values must be strings.
  \item
    Key lookups are case-insensitive.
  \item
    Duplicate keys are allowed (see \method{add()} below). When there is
    more than one value for a key, a subscript operation returns a list.
  \end{itemize}

  Much of the information that Apache uses is stored in tables. For
  example, \member{req.headers_in} and \member{req.headers_out}.

  All the tables that mod_python provides inside the request
  object are actual mappings to the Apache structures, so changing the
  Python table also changes the underlying Apache table.

  In addition to normal dictionary-like behavior, the table object also
  has the following method:

  \begin{methoddesc}[table]{add}{key, val}
    \function{add()} allows for creating duplicate keys, which is useful 
    when multiple headers, such as \code{Set-Cookie:} are required.
  \end{methoddesc}

  \versionadded{3.0}
\end{classdesc}

\subsection{Request Object\index{request}\label{pyapi-mprequest}}

The request object is a Python mapping to the Apache
\code{request_rec} structure. When a handler is invoked, it is always
passed a single argument - the request object. 

You can dynamically assign attributes to it as a way to communicate
between handlers.

\subsubsection{Request Methods\label{pyapi-mprequest-meth}}

\begin{methoddesc}[request]{add_common_vars}{}
  Calls the Apache \cfunction{ap_add_common_vars()} function. After a
  call to this method, \member{req.subprocess_env} will contain a
  lot of CGI information.
\end{methoddesc}

\begin{methoddesc}[request]{add_handler}{htype, handler\optional{, dir}}

  Allows dynamic handler registration. \var{htype} is a string
  containing the name of any of the apache request (but not filter or
  connection) handler directives,
  e.g. \samp{PythonHandler}. \var{handler} is a string containing the
  name of the module and the handler function.  Optional \var{dir} is
  a string containing the name of the directory to be added to the
  pythonpath. If no directory is specified, then, if there is already
  a handler of the same type specified, its directory is inherited,
  otherwise the directory of the presently executing handler is
  used. If there is a \code{PythonPath} directive in effect, then
  \code{sys.path} will be set exactly according to it (no directories
  added, the \var{dir} argument is ignored).
  
  A handler added this way only persists throughout the life of the
  request. It is possible to register more handlers while inside the
  handler of the same type. One has to be careful as to not to create
  an infinite loop this way.

  Dynamic handler registration is a useful technique that allows the
  code to dynamically decide what will happen next. A typical example
  might be a \code{PythonAuthenHandler} that will assign different
  \code{PythonHandlers} based on the authorization level, something
  like:

  \begin{verbatim}
if manager:
    req.add_handler("PythonHandler", "menu::admin")
else:
    req.add_handler("PythonHandler", "menu::basic")
  \end{verbatim}                              

  \begin{notice}
    If you pass this function an invalid handler, an exception will be
    generated at the time an attempt is made to find the handler. 
  \end{notice}
\end{methoddesc}

\begin{methoddesc}[request]{allow_methods}{methods\optional{, reset}}
  Adds methods to the \member{req.allowed_methods} list. This list
  will be passed in \code{Allowed:} header if
  \constant{HTTP_METHOD_NOT_ALLOWED} or \constant{HTTP_NOT_IMPLEMENTED}
  is returned to the client. Note that Apache doesn't do anything to
  restrict the methods, this list is only used to construct the
  header. The actual method-restricting logic has to be provided in the
  handler code.

  \var{methods} is a sequence of strings. If \var{reset} is 1, then
  the list of methods is first cleared.
\end{methoddesc}

\begin{methoddesc}[request]{document_root}{}
  Returns DocumentRoot setting.
\end{methoddesc}

\begin{methoddesc}[request]{get_basic_auth_pw}{}
  Returns a string containing the password when Basic authentication is
  used.
\end{methoddesc}

\begin{methoddesc}[request]{get_config}{}
  Returns a reference to the table object containing the mod_python
  configuration in effect for this request except for
  \code{Python*Handler} and \code{PythonOption} (The latter can be
  obtained via \method{req.get_options()}. The table has directives as
  keys, and their values, if any, as values.
\end{methoddesc}

\begin{methoddesc}[request]{get_remote_host}{\optional{type, str_is_ip}}

  This method is used to determine remote client's DNS name or IP
  number. The first call to this function may entail a DNS look up, but
  subsequent calls will use the cached result from the first call.

  The optional \var{type} argument can specify the following: 

  \begin{itemize}

  \item
    \code{apache.REMOTE_HOST} Look up the DNS name. Return None if Apache
    directive \code{HostNameLookups} is \code{off} or the hostname cannot
    be determined.

  \item                  
    \code{apache.REMOTE_NAME} \emph{(Default)} Return the DNS name if
    possible, or the IP (as a string in dotted decimal notation)
    otherwise.

  \item
    \code{apache.REMOTE_NOLOOKUP} Don't perform a DNS lookup, return an
    IP. Note: if a lookup was performed prior to this call, then the
    cached host name is returned.

  \item
    \code{apache.REMOTE_DOUBLE_REV} Force a double-reverse lookup. On 
    failure, return None.

  \end{itemize}

  If \var{str_is_ip} is \code{None} or unspecified, then the return
  value is a string representing the DNS name or IP address.

  If the optional \var{str_is_ip} argument is not \code{None}, then the
  return value is an \code{(address, str_is_ip)} tuple, where \var{str_is_ip}
  is non-zero if \code{address} is an IP address string.

  On failure, \code{None} is returned.

\end{methoddesc}

\begin{methoddesc}[request]{get_options}{}
  Returns a reference to the table object containing the options set by
  the \code{PythonOption} directives.
\end{methoddesc}

\begin{methoddesc}[request]{internal_redirect}{new_uri}
  Internally redirects the request to the \var{new_uri}. \var{new_uri}
  must be a string.

  The httpd server handles internal redirection by creating a new
  request object and processing all request phases. Within an internal
  redirect, \code{req.prev} will contain a reference to a request
  object from which it was redirected.

\end{methoddesc}

\begin{methoddesc}{log_error}{message\optional{, level}}
  An interface to the Apache \code{ap_log_rerror}
  function. \var{message} is a string with the error message,
  \var{level} is one of the following flags constants:

  \begin{verbatim}
    APLOG_EMERG
    APLOG_ALERT
    APLOG_CRIT
    APLOG_ERR
    APLOG_WARNING
    APLOG_NOTICE
    APLOG_INFO
    APLOG_DEBUG
    APLOG_NOERRNO
  \end{verbatim}            

  If you need to write to log and do not have a reference to a request object,
  use the \function{apache.log_error} function.
\end{methoddesc}

\begin{methoddesc}[request]{meets_conditions}{}
  Calls the Apache \cfunction{ap_meets_conditions()} function which
  returns a status code.  If \var{status} is \constant{apache.OK}, generate
  the content of the response normally.  If not, simply return \var{status}.
  Note that \member{req.headers_out} should be set prior to calling this
  function.  The same goes for \member{req.status} if the status differs
  from \constant{apache.OK}.

  Example:
  \begin{verbatim}
...
r.headers_out['ETag'] = "1130794f-3774-4584-a4ea-0ab19e684268"
r.headers_out['Last-Modified'] = 'Wed, 23 Feb 2005 00:00:00 GMT'
r.headers_out['Expires'] = 'Mon, 18 Apr 2005 17:30:00 GMT'

status = r.meets_conditions()
if status != apache.OK:
  return status

... do expensive generation of the response content ... 
\end{verbatim}

\end{methoddesc}


\begin{methoddesc}[request]{requires}{}

  Returns a tuple of strings of arguments to \code{require} directive.
  
  For example, with the following apache configuration:
  \begin{verbatim}
AuthType Basic
require user joe
require valid-user
  \end{verbatim}
  \method{requires()} would return \code{('user joe', 'valid-user')}.

\end{methoddesc}

\begin{methoddesc}[request]{read}{\optional{len}}

  Reads at most \var{len} bytes directly from the client, returning a
  string with the data read. If the \var{len} argument is negative or
  omitted, reads all data given by the client.

  This function is affected by the \code{Timeout} Apache configuration
  directive. The read will be aborted and an \exception{IOError}
  raised if the \code{Timeout} is reached while reading client data.

  This function relies on the client providing the \code{Content-length}
  header. Absence of the \code{Content-length} header will be treated as
  if \code{Content-length: 0} was supplied.

  Incorrect \code{Content-length} may cause the function to try to read
  more data than available, which will make the function block until a
  \code{Timeout} is reached.

\end{methoddesc}

\begin{methoddesc}[request]{readline}{\optional{len}}
  Like \function{read()} but reads until end of line. 
  
  \begin{notice}
    In accordance with the HTTP specification, most clients will
    be terminating lines with \samp{\e r\e n} rather
    than simply \samp{\e n}.
  \end{notice}

\end{methoddesc}

\begin{methoddesc}[request]{readlines}{\optional{sizehint}}
  Reads all or up to \var{sizehint} bytes of lines using
  \method{readline} and returns a list of the lines read.
\end{methoddesc}

\begin{methoddesc}[request]{register_cleanup}{callable\optional{, data}}

  Registers a cleanup. Argument \var{callable} can be any callable
  object, the optional argument \var{data} can be any object (default is
  \code{None}). At the very end of the request, just before the actual
  request record is destroyed by Apache, \var{callable} will be called
  with one argument, \var{data}.

  It is OK to pass the request object as data, but keep in mind that
  when the cleanup is executed, the request processing is already
  complete, so doing things like writing to the client is completely
  pointless. 

  If errors are encountered during cleanup processing, they should be in
  error log, but otherwise will not affect request processing in any
  way, which makes cleanup bugs sometimes hard to spot.

  If the server is shut down before the cleanup had a chance to run,
  it's possible that it will not be executed.

\end{methoddesc}

\begin{methoddesc}[request]{sendfile}{path\optional{, offset, len}}
  Sends \var{len} bytes of file \var{path} directly to the client,
  starting at offset \var{offset} using the server's internal
  API. \var{offset} defaults to 0, and \var{len} defaults to -1 (send
  the entire file). 

  Returns the number of bytes sent, or raises an IOError exception
  on failure.

  This function provides the most efficient way to send a file to the
  client.
\end{methoddesc}

\begin{methoddesc}[request]{write}{string\optional{, flush=1}}
  Writes \var{string} directly to the client, then flushes the buffer,
  unless flush is 0.
\end{methoddesc}

\begin{methoddesc}[request]{flush}{}
  Flushes the output buffer.
\end{methoddesc}

\begin{methoddesc}[request]{set_content_length}{len}
  Sets the value of \member{req.clength} and the \samp{Content-Length}
  header to len. Note that after the headers have been sent out (which
  happens just before the first byte of the body is written,
  i.e. first call to \member{req.write()}), calling the method is
  meaningless.
\end{methoddesc}


\subsubsection{Request Members\label{pyapi-mprequest-mem}}

\begin{memberdesc}[request]{connection}
  A \code{connection} object associated with this request. See
  Connection Object below for details.
  \emph{(Read-Only)}
\end{memberdesc}

\begin{memberdesc}[request]{server}
  A server object associate with this request. See Server Object below
  for details.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{next}
  If this is an internal redirect, the request object we redirect to. 
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{prev}
  If this is an internal redirect, the request object we redirect from.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{main}
  If this is a sub-request, pointer to the main request. 
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{the_request}
  String containing the first line of the request.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{assbackwards}
  Indicates an HTTP/0.9 ``simple'' request. This means that the
  response will contain no headers, only the body. Although this
  exists for backwards compatibility with obsolescent browsers, some
  people have figred out that setting assbackwards to 1 can be a
  useful technique when including part of the response from an
  internal redirect to avoid headers being sent.
\end{memberdesc}

\begin{memberdesc}[request]{proxyreq}
  A proxy request: one of \constant{apache.PROXYREQ_*} values.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{header_only}
  A boolean value indicating HEAD request, as opposed to GET. 
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{protocol}
  Protocol, as given by the client, or \samp{HTTP/0.9}. Same as CGI \envvar{SERVER_PROTOCOL}.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{proto_num}
  Integer. Number version of protocol; 1.1 = 1001 
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{hostname}
  String. Host, as set by full URI or Host: header.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{request_time}
  A long integer. When request started.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{status_line}
  Status line. E.g. \samp{200 OK}. 
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{status}
  Status. One of \constant{apache.HTTP_*} values.
\end{memberdesc}

\begin{memberdesc}[request]{method}
  A string containing the method - 'GET', 'HEAD', 'POST', etc.
  Same as CGI \envvar{REQUEST_METHOD}.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{method_number}
  Integer containing the method number.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{allowed}
  Integer. A bitvector of the allowed methods. Used to construct the
  Allowed: header when responding with
  \constant{HTTP_METHOD_NOT_ALLOWED} or
  \constant{HTTP_NOT_IMPLEMENTED}. This field is for Apache's internal
  use, to set the Allowed: methods use \method{req.allow_methods()}
  method, described in section \ref{pyapi-mprequest-meth}. 
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{allowed_xmethods}
  Tuple. Allowed extension methods.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{allowed_methods}
  Tuple. List of allowed methods. Used in relation with
  \constant{METHOD_NOT_ALLOWED}. This member can be modified via \method{req.allow_methods()} 
  described in section \ref{pyapi-mprequest-meth}.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{sent_bodyct}
  Integer. Byte count in stream is for body. (?)
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{bytes_sent}
  Long integer. Number of bytes sent.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{mtime}
  Long integer. Time the resource was last modified.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{chunked}
  Boolean value indicating when sending chunked transfer-coding.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{range}
  String. The \code{Range:} header.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{clength}
  Long integer. The ``real'' content length.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{remaining}
  Long integer. Bytes left to read. (Only makes sense inside a read
  operation.)
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{read_length}
  Long integer. Number of bytes read.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{read_body}
  Integer. How the request body should be read.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{read_chunked}
  Boolean. Read chunked transfer coding.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{expecting_100}
  Boolean. Is client waiting for a 100 (\constant{HTTP_CONTINUE}) response.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{headers_in}
  A table object containing headers sent by the client.
\end{memberdesc}

\begin{memberdesc}[request]{headers_out}
  A \code{table} object representing the headers to be sent to the
  client. 
\end{memberdesc}

\begin{memberdesc}[request]{err_headers_out}
  These headers get send with the error response, instead of
  headers_out.
\end{memberdesc}

\begin{memberdesc}[request]{subprocess_env}
  A \code{table} object containing environment information typically usable for CGI.
  You may have to call \member{req.add_common_vars()} first to fill in the information
  you need.
\end{memberdesc}

\begin{memberdesc}[request]{notes}
  A \code{table} object that could be used to store miscellaneous
  general purpose info that lives for as long as the request lives. If
  you need to pass data between handlers, it's better to simply add
  members to the request object than to use \member{notes}.
\end{memberdesc}

\begin{memberdesc}[request]{phase}
  The phase currently being being processed, e.g. \samp{PythonHandler}.
  \emph{(Read-Only)}
\end{memberdesc}

\begin{memberdesc}[request]{interpreter}
  The name of the subinterpreter under which we're running.
  \emph{(Read-Only)}
\end{memberdesc}

\begin{memberdesc}[request]{content_type}
  String. The content type. Mod_python maintains an internal flag
  (\member{req._content_type_set}) to keep track of whether
  \member{content_type} was set manually from within Python. The
  publisher handler uses this flag in the following way: when
  \member{content_type} isn't explicitly set, it attempts to guess the
  content type by examining the first few bytes of the output.
\end{memberdesc}

\begin{memberdesc}[request]{content_languages}
  Tuple. List of strings representing the content languages. 
\end{memberdesc}

\begin{memberdesc}[request]{handler}
  The name of the handler currently being processed. This is the handler
  set by mod_mime, not the mod_python handler. In most cases it will be
  "\samp{mod_python}. \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{content_encoding}
  String. Content encoding.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{vlist_validator}
  Integer. Variant list validator (if negotiated).
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{user}
  If an authentication check is made, this will hold the user
  name. Same as CGI \envvar{REMOTE_USER}.
  \emph{(Read-Only})
  \begin{notice}
    \method{req.get_basic_auth_pw()} must be called prior to using this value.
  \end{notice}
\end{memberdesc}

\begin{memberdesc}[request]{ap_auth_type}
  Authentication type. Same as CGI \envvar{AUTH_TYPE}.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{no_cache}
  Boolean. No cache if true.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{no_local_copy}
  Boolean. No local copy exists.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{unparsed_uri}
  The URI without any parsing performed.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{uri}
  The path portion of the URI.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{filename}
  String. File name being requested.
\end{memberdesc}

\begin{memberdesc}[request]{canonical_filename}
  String. The true filename (\member{req.filename} is canonicalized if
  they don't match).  \emph{(Read-Only)}
\end{memberdesc}

\begin{memberdesc}[request]{path_info}
  String. What follows after the file name, but is before query args, if
  anything. Same as CGI \envvar{PATH_INFO}.
\end{memberdesc}

\begin{memberdesc}[request]{args}
  String. Same as CGI \envvar{QUERY_ARGS}.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{finfo}
  Tuple. A file information structure, analogous to POSIX stat,
  describing the file pointed to by the URI.  \code{(mode, ino,
    dev, nlink, uid, gid, size, atime, mtime, ctime, fname,
    name)}. The \code{apache} module defines a set of \constant{FINFO_*}
  constants that should be used to access elements of this
  tuple. Example:
  \begin{verbatim}
fname = req.finfo[apache.FINFO_FNAME]
  \end{verbatim}
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{parsed_uri}
  Tuple. The URI broken down into pieces.
  \code{(scheme, hostinfo, user, password, hostname, port, path, query, fragment)}. 
  The \code{apache} module defines a set of \constant{URI_*} constants that
  should be used to access elements of this tuple. Example:
  \begin{verbatim}
fname = req.parsed_uri[apache.URI_PATH]
  \end{verbatim}
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{used_path_info}
  Flag to accept or reject path_info on current request.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[request]{eos_sent}
  Boolean. EOS bucket sent.
  \emph{(Read-Only})
\end{memberdesc}

\subsection{Connection Object (mp_conn)\obindex{connection}\label{pyapi-mpconn}}

The connection object is a Python mapping to the Apache conn_rec
structure.

\subsubsection{Connection Methods\label{pyapi-mpconn-meth}}

\begin{methoddesc}[connection]{read}{\optional{length}}
  Reads at most \var{length} bytes from the client. The read blocks
  indefinitely until there is at least one byte to read. If length is
  -1, keep reading until the socket is closed from the other end (This
  is known as \code{EXHAUSTIVE} mode in the http server code).

  This method should only be used inside \emph{Connection Handlers}.

  \begin{notice}
    The behaviour of this method has changed since version 3.0.3. In
    3.0.3 and prior, this method would block until \var{length} bytes
    was read.
  \end{notice}

\end{methoddesc}

\begin{methoddesc}[connection]{readline}{\optional{length}}

  Reads a line from the connection or up to \var{length} bytes.

  This method should only be used inside \emph{Connection Handlers}.

\end{methoddesc}

\begin{methoddesc}[connection]{write}{string}

  Writes \var{string} to the client.

  This method should only be used inside \emph{Connection Handlers}.

\end{methoddesc}

\subsubsection{Connection Members\label{pyapi-mpconn-mem}}

\begin{memberdesc}[connection]{base_server}
  A \code{server} object for the physical vhost that this connection came in
  through.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{local_addr}
  The (address, port) tuple for the server.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{remote_addr}
  The (address, port) tuple for the client.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{remote_ip}
  String with the IP of the client. Same as CGI \envvar{REMOTE_ADDR}.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{remote_host}
  String. The DNS name of the remote client. None if DNS has not been
  checked, \code{""} (empty string) if no name found. Same as CGI \envvar{REMOTE_HOST}.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{remote_logname}
  Remote name if using RFC1413 (ident). Same as CGI \envvar{REMOTE_IDENT}.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{aborted}
  Boolean. True is the connection is aborted.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{keepalive}
  Integer. 1 means the connection will be kept for the next request, 0 means
  ``undecided'', -1 means ``fatal error''.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{double_reverse}
  Integer. 1 means double reverse DNS lookup has been performed, 0 means
  not yet, -1 means yes and it failed.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{keepalives}
  The number of times this connection has been used. (?)
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{local_ip}
  String with the IP of the server.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{local_host}
  DNS name of the server.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{id}
  Long. A unique connection id.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[connection]{notes}
  A \code{table} object containing miscellaneous general purpose info that lives for
  as long as the connection lives. 
\end{memberdesc}

\subsection{Filter Object (mp_filter)\obindex{filter}\label{pyapi-mpfilt}}

A filter object is passed to mod_python input and output filters. It
is used to obtain filter information, as well as get and pass
information to adjacent filters in the filter stack.

\subsubsection{Filter Methods\label{pyapi-mpfilt-meth}}

\begin{methoddesc}[filter]{pass_on}{}
  Passes all data through the filter without any processing.
\end{methoddesc}

\begin{methoddesc}[filter]{read}{\optional{length}}
  Reads at most \var{len} bytes from the next filter, returning a string
  with the data read or None if End Of Stream (EOS) has been reached. A
  filter \emph{must} be closed once the EOS has been encountered.

  If the \var{len} argument is negative or omitted, reads all data
  currently available.
\end{methoddesc}

\begin{methoddesc}[filter]{readline}{\optional{length}}
  Reads a line from the next filter or up to \var{length} bytes.
\end{methoddesc}

\begin{methoddesc}[filter]{write}{string}
  Writes \var{string} to the next filter.
\end{methoddesc}

\begin{methoddesc}[filter]{flush}{}
  Flushes the output by sending a FLUSH bucket.
\end{methoddesc}

\begin{methoddesc}[filter]{close}{}
  Closes the filter and sends an EOS bucket. Any further IO operations on
  this filter will throw an exception.
\end{methoddesc}

\begin{methoddesc}[filter]{disable}{}
  Tells mod_python to ignore the provided handler and just pass the data
  on. Used internally by mod_python to print traceback from exceptions
  encountered in filter handlers to avoid an infinite loop.
\end{methoddesc}

\subsubsection{Filter Members\label{pyapi-mpfilt-mem}}

\begin{memberdesc}[filter]{closed}
  A boolean value indicating whether a filter is closed.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[filter]{name}
  String. The name under which this filter is registered.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[filter]{req}
  A reference to the request object.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[filter]{is_input}
  Boolean. True if this is an input filter.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[filter]{handler}
  String. The name of the Python handler for this filter as specified in
  the configuration. 
  \emph{(Read-Only})
\end{memberdesc}

\subsection{Server Object (mp_server)\obindex{server}\label{pyapi-mpserver}}

The request object is a Python mapping to the Apache \code{request_rec}
structure. The server structure describes the server (possibly virtual
server) serving the request.

\subsubsection{Server Methods\label{pyapi-mpsrv-meth}}

\begin{methoddesc}[server]{get_config}{}
  Similar to \code{req.get_config()}, but returns a config pointed to
  by \code{server->module_config} Apache config vector. 
\end{methoddesc}

\begin{methoddesc}[server]{register_cleanup}{request, callable\optional{, data}}
  Registers a cleanup. Very similar to \function{req.register_cleanup()}, except
  this cleanup will be executed at child termination time. This function
  requires one extra argument - the request object.
\end{methoddesc}

\subsubsection{Server Members\label{pyapi-mpsrv-mem}}

\begin{memberdesc}[server]{defn_name}
  String. The name of the configuration file where the server definition
  was found.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{defn_line_number}
  Integer. Line number in the config file where the server definition is
  found.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{server_admin}
  Value of the \code{ServerAdmin} directive. 
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{server_hostname}
  Value of the \code{ServerName} directive. Same as CGI \envvar{SERVER_NAME}.\emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{names}
  Tuple. List of normal server names specified in the \code{ServerAlias} 
  directive.  This list does not include wildcarded names, which are listed
  separately in \code{wild_names}. \emph{(Read-Only)}
\end{memberdesc}

\begin{memberdesc}[server]{wild_names}
  Tuple. List of wildcarded server names specified in the \code{ServerAlias}
  directive. \emph{(Read-Only)}
\end{memberdesc}

\begin{memberdesc}[server]{port}
  Integer. TCP/IP port number. Same as CGI \envvar{SERVER_PORT}.
  \emph{This member appears to be 0 on Apache 2.0, look at req.connection.local_addr instead}
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{error_fname}
  The name of the error log file for this server, if any.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{loglevel}
  Integer. Logging level.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{is_virtual}
  Boolean. True if this is a virtual server.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{timeout}
  Integer. Value of the \code{Timeout} directive.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{keep_alive_timeout}
  Integer. Keepalive timeout.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{keep_alive_max}
  Maximum number of requests per keepalive.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{keep_alive}
  Use persistent connections?
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{path}
  String. Path for \code{ServerPath}
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{pathlen}
  Integer. Path length.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{limit_req_line}
  Integer. Limit on size of the HTTP request line.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{limit_req_fieldsize}
  Integer. Limit on size of any request header field.
  \emph{(Read-Only})
\end{memberdesc}

\begin{memberdesc}[server]{limit_req_fields}
  Integer. Limit on number of request header fields.
  \emph{(Read-Only})
\end{memberdesc}

\section{\module{util} -- Miscellaneous Utilities\label{pyapi-util}}
\declaremodule[util]{extension}{util}
\modulesynopsis{Miscellaneous Utilities}
\moduleauthor{Gregory Trubetskoy}{grisha@apache.org}

The \module{util} module provides a number of utilities handy to a web
application developer similar to those in the standard library
\module{cgi} module. The implementations in the \module{util} module
are much more efficient because they call directly into Apache API's
as opposed to using CGI which relies on the environment to pass
information.

The recommended way of using this module is:
\begin{verbatim}
from mod_python import util
\end{verbatim}

\begin{seealso}
  \seetitle[http://CGI-Spec.Golux.Com/]
           {Common Gateway Interface RFC Project Page}
           {for detailed information on the CGI specification}
\end{seealso}

\subsection{FieldStorage class\label{pyapi-util-fstor}}

Access to form data is provided via the \class{FieldStorage}
class. This class is similar to the standard library module
\module{cgi} \class{FieldStorage}.

\begin{classdesc}{FieldStorage}{req\optional{, keep_blank_values, strict_parsing}}
  This class provides uniform access to HTML form data submitted by the
  client.  \var{req} is an instance of the mod_python request object.

  The optional argument \var{keep_blank_values} is a flag indicating
  whether blank values in URL encoded form data should be treated as
  blank strings. The default is false, which means that blank values are
  ignored as if they were not included.

  The optional argument \var{strict_parsing} is not yet implemented.

  During initialization, \class{FieldStorage} class reads all of the
  data provided by the client. Since all data provided by the client is
  consumed at this point, there should be no more than one
  \class{FieldStorage} class instantiated per single request, nor should
  you make any attempts to read client data before or after
  instantiating a \class{FieldStorage}.

  The data read from the client is then parsed into separate fields and
  packaged in \class{Field} objects, one per field. For HTML form inputs
  of type \code{file}, a temporary file is created that can later be
  accessed via the \member{file} attribute of a \class{Field} object.

  The \class{FieldStorage} class has a mapping object interface, i.e. it
  can be treated like a dictionary. When used as a mapping, the keys are
  form input names, and the returned dictionary value can be:

  \begin{itemize}
  \item
    An instance of \class{StringField}, containing the form input
    value. This is only when there is a single value corresponding to the
    input name. \class{StringField} is a subclass of \class{str} which
    provides the additional \member{value} attribute for compatibility
    with standard library \module{cgi} module.
  \item
    An instance of a \class{Field} class, if the input is a file upload.
  \item
    A list of \class{StringField} and/or \class{Field} objects. This is
    when multiple values exist, such as for a \code{<select>} HTML form
    element.
  \end{itemize}

  \begin{notice}
    Unlike the standard library \module{cgi} module
    \class{FieldStorage} class, a \class{Field} object is returned
    \emph{only} when it is a file upload. In all other cases the
    return is an instance of \class{StringField}. This means that you
    do not need to use the \member{.value} attribute to access values
    of fields in most cases.
  \end{notice}

  In addition to standard mapping object methods, \class{FieldStorage} objects
  have the following attributes:

  \begin{memberdesc}{list}
    This is a list of \class{Field} objects, one for each input. Multiple
    inputs with the same name will have multiple elements in this list.
  \end{memberdesc}

  \class{FieldStorage} methods:

  \begin{methoddesc}[FieldStorage]{getfirst}{name\optional{, default}}
    Always returns only one value associated with form field
    \var{name}. If no such form field or value exists then the method
    returns the value specified by the optional parameter
    \var{default}. This parameter defaults to \code{None} if not
    specified.
  \end{methoddesc}

  \begin{methoddesc}[FieldStorage]{getlist}{name}
    This method always returns a list of values associated with form
    field \var{name}. The method returns an empty list if no such form
    field or value exists for \var{name}. It returns a list consisting
    of one item if only one such value exists.
  \end{methoddesc}

\end{classdesc}

\subsection{Field class\label{pyapi-util-fstor-fld}}

\begin{classdesc}{Field}{}
  This class is used internally by \class{FieldStorage} and is not
  meant to be instantiated by the user. Each instance of a \class{Field}
  class represents an HTML Form input.

  \class{Field} instances have the following attributes:

  \begin{memberdesc}{name}
    The input name.
  \end{memberdesc}

  \begin{memberdesc}{value}
    The input value. This attribute can be used to read data from a file
    upload as well, but one has to exercise caution when dealing with
    large files since when accessed via \member{value}, the whole file is
    read into memory.
  \end{memberdesc}

  \begin{memberdesc}{file}
    This is a file-like object. For file uploads it points to a 
    \class{TemporaryFile} instance. (For more information see the TemporaryFile
    class in the standard python
    \citetitle[http://docs.python.org/lib/module-tempfile.html]{tempfile} module).

    For simple values, it is a \class{StringIO} object, so you can read
    simple string values via this attribute instead of using the \member{value}
    attribute as well.
  \end{memberdesc}

  \begin{memberdesc}{filename}
    The name of the file as provided by the client.
  \end{memberdesc}

  \begin{memberdesc}{type}
    The content-type for this input as provided by the client.
  \end{memberdesc}

  \begin{memberdesc}{type_options}
    This is what follows the actual content type in the \code{content-type}
    header provided by the client, if anything. This is a dictionary.
  \end{memberdesc}

  \begin{memberdesc}{disposition}
    The value of the first part of the \code{content-disposition} header.
  \end{memberdesc}

  \begin{memberdesc}{disposition_options}
    The second part (if any) of the \code{content-disposition} header in
    the form of a dictionary.
  \end{memberdesc}

  \begin{seealso}
    \seerfc{1867}{Form-based File Upload in HTML}{for a description of 
      form-based file uploads}
  \end{seealso}
\end{classdesc}

\subsection{Other functions\label{pyapi-util-funcs}}

\begin{funcdesc}{parse_qs}{qs\optional{, keep_blank_values, strict_parsing}}

  This function is functionally equivalent to the standard library
  \module{cgi} \function{parse_qs}, except that it is written in C and is
  much faster. 

  Parse a query string given as a string argument (data of type
  \mimetype{application/x-www-form-urlencoded}).  Data are
  returned as a dictionary.  The dictionary keys are the unique query
  variable names and the values are lists of values for each name.

  The optional argument \var{keep_blank_values} is a flag indicating
  whether blank values in URL encoded queries should be treated as blank
  strings.  A true value indicates that blanks should be retained as
  blank strings.  The default false value indicates that blank values
  are to be ignored and treated as if they were not included.

  \begin{notice}
    The \var{strict_parsing} argument is not yet implemented.
  \end{notice}

\end{funcdesc}


\begin{funcdesc}{parse_qsl}{qs\optional{, keep_blank_values, strict_parsing}}

  This function is functionally equivalent to the standard library
  \module{cgi} \function{parse_qsl}, except that it is written in C and is
  much faster. 

  Parse a query string given as a string argument (data of type
  \mimetype{application/x-www-form-urlencoded}).  Data are
  returned as a list of name, value pairs.

  The optional argument \var{keep_blank_values} is a flag indicating
  whether blank values in URL encoded queries should be treated as blank
  strings.  A true value indicates that blanks should be retained as
  blank strings.  The default false value indicates that blank values
  are to be ignored and treated as if they were not included.

  \begin{notice}
    The \var{strict_parsing} argument is not yet implemented.
  \end{notice}

\end{funcdesc}

\begin{funcdesc}{redirect}{req, location\optional{, permanent=0, text=None}}
  This is a convenience function to redirect the browser to another
  location. When \var{permanent} is true, \constant{MOVED_PERMANENTLY}
  status is sent to the client, otherwise it is
  \constant{MOVED_TEMPORARILY}. A short text is sent to the browser
  informing that the document has moved (for those rare browsers that
  do not support redirection); this text can be overridden by
  supplying a \var{text} string.

  If this function is called after the headers have already been sent,
  an \exception{IOError} is raised.

  This function raises \exception{apache.SERVER_RETURN} exception to
  abandon any further processing of the handle. If you do not want
  this, you can wrap the call to \function{redirect} in a try/except
  block catching the \exception{apache.SERVER_RETURN}.
\end{funcdesc}

\section{\module{Cookie} -- HTTP State Management\label{pyapi-cookie}}
\declaremodule[Cookie]{extension}{Cookie}
\modulesynopsis{HTTP State Management}
\moduleauthor{Gregory Trubetskoy}{grisha@apache.org}

The \module{Cookie} module provides convenient ways for creating,
parsing, sending and receiving HTTP Cookies, as defined in the
specification published by Netscape.

\begin{notice}
  Even though there are official IETF RFC's describing HTTP State
  Management Mechanism using cookies, the de facto standard supported
  by most browsers is the original Netscape specification.
  Furthermore, true compliance with IETF standards is actually
  incompatible with many popular browsers, even those that claim to be
  RFC-compliant. Therefore, this module supports the current common
  practice, and is not fully RFC compliant.
  
  More specifically, the biggest difference between Netscape and RFC cookies is 
  that RFC cookies are sent from the browser to the server along with their 
  attributes (like Path or Domain). The \module{Cookie} module ignore those 
  incoming attributes, so all incoming cookies end up as Netscape-style cookies, 
  without any of their attributes defined.
\end{notice}

\begin{seealso}
  \seetitle[http://wp.netscape.com/newsref/std/cookie_spec.html]
           {Persistent Client State - HTTP Cookies}{for the original Netscape specification.}
           \seerfc{2109}{HTTP State Management Mechanism}{for the first RFC on Cookies.}
           \seerfc{2964}{Use of HTTP State Management}{for guidelines on using Cookies.}
           \seerfc{2965}{HTTP State Management Mechanism}{for the latest IETF standard.}
           \seetitle[http://arxiv.org/abs/cs.SE/0105018]
                    {HTTP Cookies: Standards, Privacy, and Politics}{by David M. Kristol for an 
                      excellent overview
                      of the issues surrounding standardization of Cookies.}
\end{seealso}

\subsection{Classes\label{pyapi-cookie-classes}}

\begin{classdesc}{Cookie}{name, value\optional{, attributes}}

  This class is used to construct a single cookie named \var{name}
  and having \var{value} as the value. Additionally, any of the 
  attributes defined in the Netscape specification and RFC2109 can by
  supplied as keyword arguments.

  The attributes of the class represent cookie attributes, and their
  string representations become part of the string representation of
  the cookie. The \class{Cookie} class restricts attribute names to
  only valid values, specifically, only the following attributes are
  allowed: \code{name, value, version, path, domain, secure, comment,
  expires, max_age, commentURL, discard, port, __data__}.

  The \code{__data__} attribute is a general-purpose dictionary that
  can be used for storing arbitrary values, when necessary (This is
  useful when subclassing \class{Cookie}).

  The \member{expires} attribute is a property whose value is checked
  upon setting to be in format \samp{Wdy, DD-Mon-YYYY HH:MM:SS GMT}
  (as dictated per Netscape cookie specification), or a numeric value
  representing time in seconds since beginning of epoch (which will be
  automatically correctly converted to GMT time string). An invalid
  \code{expires} value will raise \exception{ValueError}.

  When converted to a string, a \class{Cookie} will be in correct
  format usable as value in a \samp{Cookie} or \samp{Set-Cookie}
  header.

  \begin{notice}
    Unlike the Python Standard Library Cookie classes, this
    class represents a single cookie (referred to as \dfn{Morsel} in
    Python Standard Library).
  \end{notice}

  \begin{methoddesc}[Cookie]{parse}{string}
    This is a class method that can be used to create a \class{Cookie}
    instance from a cookie string \var{string} as passed in a header
    value. During parsing, attribute names are converted to lower
    case.

    Because this is a class method, it must be called explicitly
    specifying the class.

    This method returns a dictionary of \class{Cookie} instances, not
    a single \class{Cookie} instance.

    Here is an example of getting a single \class{Cookie} instance:
    \begin{verbatim}
mycookies = Cookie.parse("spam=eggs; expires=Sat, 14-Jun-2003 02:42:36 GMT")
spamcookie = mycookies["spam"]
    \end{verbatim}

    \begin{notice}
      Because this method uses a dictionary, it is not possible to
      have duplicate cookies. If you would like to have more than one
      value in a single cookie, consider using a \class{MarshalCookie}.
    \end{notice}

  \end{methoddesc}

\end{classdesc}

\begin{classdesc}{SignedCookie}{name, value, secret\optional{, attributes}}

  This is a subclass of \class{Cookie}. This class creates cookies
  whose name and value are automatically signed using HMAC (md5) with
  a provided secret \var{secret}, which must be a non-empty string.

  \begin{methoddesc}[SignedCookie]{parse}{string, secret}
    This method acts the same way as \class{Cookie.parse()}, but also
    verifies that the cookie is correctly signed. If the signature
    cannot be verified, the object returned will be of class
    \class{Cookie}.

    \begin{notice}
      Always check the types of objects returned by
      \method{SignedCookie.parse()}.If it is an instance of
      \class{Cookie} (as opposed to \class{SignedCookie}), the
      signature verification has failed:
      \begin{verbatim}
# assume spam is supposed to be a signed cookie
if type(spam) is not Cookie.SignedCookie:
    # do something that indicates cookie isn't signed correctly
      \end{verbatim}
    \end{notice}
  \end{methoddesc}

\end{classdesc}

\begin{classdesc}{MarshalCookie}{name, value, secret\optional{, attributes}}

  This is a subclass of \class{SignedCookie}. It allows for
  \var{value} to be any marshallable objects. Core Python types such as
  string, integer, list, etc. are all marshallable object. For a
  complete list see
  \citetitle[http://www.python.org/doc/current/lib/module-marshal.html]{marshal}
  module documentation.

  When parsing, the signature is checked first, so incorrectly signed cookies
  will not be unmarshalled.

\end{classdesc}

\subsection{Functions\label{pyapi-cookie-func}}

\begin{funcdesc}{add_cookie}{req, cookie\optional{, value, attributes}}
  This is a convenience function for setting a cookie in request
  headers. \var{req} is a mod_python \class{Request} object.  If
  \var{cookie} is an instance of \class{Cookie} (or subclass thereof),
  then the cookie is set, otherwise, \var{cookie} must be a string, in
  which case a \class{Cookie} is constructed using \var{cookie} as
  name, \var{value} as the value, along with any valid \class{Cookie}
  attributes specified as keyword arguments.

  This function will also set \samp{Cache-Control:
  no-cache="set-cookie"} header to inform caches that the cookie value
  should not be cached.

  Here is one way to use this function:
  \begin{verbatim}
c = Cookie.Cookie('spam', 'eggs', expires=time.time()+300)
Cookie.add_cookie(req, c)
  \end{verbatim}
  Here is another:
  \begin{verbatim}
Cookie.add_cookie(req, 'spam', 'eggs', expires=time.time()+300)
  \end{verbatim}
\end{funcdesc}

\begin{funcdesc}{get_cookies}{req \optional{, Class, data}}
  This is a convenience function for retrieving cookies from incoming
  headers. \var{req} is a mod_python \class{Request}
  object. \var{Class} is a class whose \method{parse()} method will be
  used to parse the cookies, it defaults to \code{Cookie}. \var{Data}
  can be any number of keyword arguments which, will be passed to
  \method{parse()} (This is useful for \class{signedCookie} and
  \class{MarshalCookie} which require \code{secret} as an additional
  argument to \method{parse}).
\end{funcdesc}

\subsection{Examples\label{pyapi-cookie-example}}

This example sets a simple cookie which expires in 300 seconds:

\begin{verbatim}
from mod_python import Cookie, apache
import time

def handler(req):

    cookie = Cookie.Cookie('eggs', 'spam')
    cookie.expires = time.time() + 300
    Cookie.add_cookie(req, cookie)

    req.write('This response contains a cookie!\n')
    return apache.OK

\end{verbatim}

This example checks for incoming marshal cookie and displays it to the
client. If no incoming cookie is present a new marshal cookie is set.
This example uses \samp{secret007} as the secret for HMAC signature.

\begin{verbatim}
from mod_python import apache, Cookie

def handler(req):
    
    cookies = Cookie.get_cookies(req, Cookie.MarshalCookie,
                                    secret='secret007')
    if cookies.has_key('spam'):
        spamcookie = cookies['spam']

        req.write('Great, a spam cookie was found: %s\n' \
                                      % str(spamcookie))
        if type(spamcookie) is Cookie.MarshalCookie:
            req.write('Here is what it looks like decoded: %s=%s\n'
                      % (spamcookie.name, spamcookie.value))
        else:
            req.write('WARNING: The cookie found is not a \
                       MarshalCookie, it may have been tapered with!')

    else:

        # MarshaCookie allows value to be any marshallable object
        value = {'egg_count': 32, 'color': 'white'}
        Cookie.add_cookie(req, Cookie.MarshalCookie('spam', value, \
                          'secret007'))
        req.write('Spam cookie not found, but we just set one!\n')

    return apache.OK
\end{verbatim}

\section{\module{Session} -- Session Management\label{pyapi-sess}}
\declaremodule[Session]{extension}{Session}
\modulesynopsis{Session Management}
\moduleauthor{Gregory Trubetskoy}{grisha@apache.org}

The \module{Session} module provides objects for maintaining persistent
sessions across requests.

The module contains a \class{BaseSession} class, which is not meant to
be used directly (it provides no means of storing a session), 
\class{DbmSession} class, which uses a dbm to store sessions, and
\class{FileSession} class, which uses individual files to store
sessions.

The \class{BaseSession} class also provides session locking, both
across processes and threads. For locking it uses APR global_mutexes
(a number of them is pre-created at startup) The mutex number is
computed by using modulus of the session id
\function{hash()}. (Therefore it's possible that different session
id's will have the same hash, but the only implication is that those
two sessions cannot be locked at the same time resulting in a slight
delay.)

\subsection{Classes\label{pyapi-sess-classes}}

\begin{funcdesc}{Session}{req\optional{, sid, secret, timeout, lock}}

  \function{Session()} takes the same arguments as \class{BaseSession}.

  This function returns a instance of the default session class. The
  the session class to be used can be specified using 
  \var{PythonOption session value}, where \var{value} is one of
  \class{DbmSession}, \class{MemorySession} or \class{FileSession}. Specifying
  custom session classes using PythonOption session is not yet supported.

  If \var{PythonOption session} is not found, the function queries
  the MPM and based on that returns either a new instance of
  \class{DbmSession} or \class{MemorySession}.
  
  \class{MemorySession} will be used if the MPM is threaded and not
  forked (such is the case on Windows), or if it threaded, forked, but
  only one process is allowed (the worker MPM can be configured to run
  this way). In all other cases \class{DbmSession} is used.
\end{funcdesc}

\begin{classdesc}{BaseSession}{req\optional{, sid, secret, timeout, lock}}

  This class is meant to be used as a base class for other classes
  that implement a session storage mechanism. \var{req} is a required
  reference to a mod_python request object.

  \class{BaseSession} is a subclass of \class{dict}. Data can be
  stored and retrieved from the session by using it as a
  dictionary. 

  \var{sid} is an optional session id; if provided, such a session
  must already exist, otherwise it is ignored and a new session with a
  new sid is created. If \var{sid} is not provided, the object will
  attempt to look at cookies for session id. If a sid is found in
  cookies, but it is not previously known or the session has expired,
  then a new sid is created. Whether a session is ``new'' can be
  determined by calling the \method{is_new()} method.

  Cookies generated by sessions will have a path attribute which is
  calculated by comparing the server \code{DocumentRoot} and the
  directory in which the \code{PythonHandler} directive currently in
  effect was specified. E.g. if document root is \file{/a/b/c} and
  \code{PythonHandler} was specified in \file{/a/b/c/d/e}, the path
  will be set to \file{/d/e}. You can force a specific path by using
  \code{ApplicationPath} option (\samp{PythonOption ApplicationPath
  /my/path} in server configuration).

  When a \var{secret} is provided, \class{BaseSession} will use
  \class{SignedCookie} when generating cookies thereby making the
  session id almost impossible to fake. The default is to use plain
  \class{Cookie} (though even if not signed, the session id is
  generated to be very difficult to guess).

  A session will timeout if it has not been accessed for more than
  \var{timeout}, which defaults to 30 minutes. An attempt to load an
  expired session will result in a ``new'' session.

  The \var{lock} argument (defaults to 1) indicates whether locking
  should be used. When locking is on, only one session object with a
  particular session id can be instantiated at a time.

  A session is in ``new'' state when the session id was just
  generated, as opposed to being passed in via cookies or the
  \var{sid} argument.


  \begin{methoddesc}[BaseSession]{is_new}{}
    Returns 1 if this session is new. A session will also be ``new''
    after an attempt to instantiate an expired or non-existent
    session. It is important to use this method to test whether an
    attempt to instantiate a session has succeeded, e.g.:
    \begin{verbatim}
sess = Session(req)
if sess.is_new():
    # redirect to login
    util.redirect(req, 'http://www.mysite.com/login')
    \end{verbatim}
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{id}{}
    Returns the session id.
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{created}{}
    Returns the session creation time in seconds since beginning of
    epoch.
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{last_accessed}{}
    Returns last access time in seconds since beginning of epoch.
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{timeout}{}
    Returns session timeout interval in seconds.
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{set_timeout}{secs}
    Set timeout to \var{secs}.
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{invalidate}{}
    This method will remove the session from the persistent store and
    also place a header in outgoing headers to invalidate the session
    id cookie.
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{load}{}
    Load the session values from storage.
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{save}{}
    This method writes session values to storage.
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{delete}{}
    Remove the session from storage.
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{init_lock}{}
    This method initializes the session lock. There is no need to ever
    call this method, it is intended for subclasses that wish to use
    an alternative locking mechanism.
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{lock}{}
    Locks this session. If the session is already locked by another
    thread/process, wait until that lock is released. There is no need
    to call this method if locking is handled automatically (default).

    This method registeres a cleanup which always unlocks the session
    at the end of the request processing.
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{unlock}{}
    Unlocks this session. (Same as \method{lock()} - when locking is
    handled automatically (default), there is no need to call this
    method).
  \end{methoddesc}

  \begin{methoddesc}[BaseSession]{cleanup}{}
    This method is for subclasses to implement session storage
    cleaning mechanism (i.e. deleting expired sessions, etc.). It will
    be called at random, the chance of it being called is controlled
    by \constant{CLEANUP_CHANCE} \module{Session} module variable
    (default 1000). This means that cleanups will be ordered at random
    and there is 1 in 1000 chance of it happening. Subclasses
    implementing this method should not perform the (potentially time
    consuming) cleanup operation in this method, but should instead
    use \method{req.register_cleanup} to register a cleanup which will
    be executed after the request has been processed.
  \end{methoddesc}

\end{classdesc}

\begin{classdesc}{DbmSession}{req, \optional{, dbm, sid, secret, dbmtype, timeout, lock}}

  This class provides session storage using a dbm file. Generally, dbm
  access is very fast, and most dbm implementations memory-map files
  for faster access, which makes their performance nearly as fast as
  direct shared memory access.

  \var{dbm} is the name of the dbm file (the file must be writable by
  the httpd process). This file is not deleted when the server process
  is stopped (a nice side benefit of this is that sessions can survive
  server restarts). By default the session information is stored in a
  dbmfile named \file{mp_sess.dbm} and stored in a temporary directory
  returned by \code{tempfile.gettempdir()} standard library
  function. An alternative directory can be specified with the  
  \code{PythonOption session_directory} directive.  
  The path and filename can can be overridden by setting \code{PythonOption
  session_dbm filename}.

  The implementation uses Python \module{anydbm} module, which will
  default to \module{dbhash} on most systems. If you need to use a
  specific dbm implementation (e.g. \module{gdbm}), you can pass that
  module as \var{dbmtype}.

  Note that using this class directly is not cross-platform. For best
  compatibility across platforms, always use the \function{Session()}
  function to create sessions.

\end{classdesc}

\begin{classdesc}{FileSession}{req, \optional{, sid, secret, timeout, lock, fast_cleanup, verify_cleanup}}

  New in version 3.2.0.

  This class provides session storage using a separate file for each
  session. It is a subclass of \module{BaseSession}.

  Session data is stored in a separate file for each session. These 
  files are not deleted when the server process is stopped, so
  sessions are persistent across server restarts.  
  The session files are saved in a directory named mp_sess in the 
  temporary directory returned by the \code{tempfile.gettempdir()} 
  standard library function. An alternate path can be set using 
  \code{PythonOption session_directory /path/to/directory}. This
  directory must exist and be readable and writeable by the apache
  process.
  
  Expired session files are periodically removed by the cleanup
  mechanism. The behaviour of the cleanup can be controlled using the 
  \var{fast_cleanup} and \var{verify_cleanup} parameters, as well as 
  \var{PythonOption session_grace_period} and
  \var{PythonOption session_cleanup_time_limit}.

  \begin{itemize}
  \item
   \var{fast_cleanup}
    A boolean value used to turn on FileSession cleanup optimization.
    Default is \var{True} and will result in reduced cleanup time when
    there are a large number of session files.
  
    When \var{fast_cleanup} is True, the modification time for the session
    file is used to determine if it is a candidate for deletion.
    If \code{(current_time - file_modification_time) > (timeout + grace_period)},
    the file will be a candidate for deletion. If \var{verify_cleanup}
    is False, no futher checks will be made and the file will be
    deleted.
    
    If \var{fast_cleanup} is False, the session file will unpickled and
    it's timeout value used to determine if the session is a candidate for
    deletion. \var{fast_cleanup} = False implies \var{verify_cleanup} =
    True.

    The timeout used in the fast_cleanup calculation is same as the
    timeout for the session in the current request running the
    filesession_cleanup. If your session objects are not using the same
    timeout, or you are manually setting the timeout for a particular
    session with \code{set_timeout()}, you will need to set 
    \var{verify_cleanup} = True.

    The value of \var{fast_cleanup} can also be set using
    \code{PythonOption session_fast_cleanup}.
    
  \item
   \var{verify_cleanup}
    Boolean value used to optimize the FileSession cleanup process.
    Default is \code{True}.
    
    If \var{verify_cleanup} is True, the session file which is being 
    considered for deletion will be unpickled and its timeout value
    will be used to decide if the file should be deleted. 
    
    When \var{verify_cleanup} is False, the timeout value for the current
    session will be used in to determine if the session has expired. In
    this case, the session data will not be read from disk, which can
    lead to a substantial performance improvement when there are a large
    number of session files, or where each session is saving a large 
    amount of data. However this may result in valid sessions being
    deleted if all the sessions are not using a the same timeout value.
    
    The value of \var{verify_cleanup} can also be set using
    \code{PythonOption session_verify_cleanup}
    
  \item
   \var{PythonOption session_cleanup_time_limit [value]}
    Integer value in seconds. Default is 2 seconds.

    Session cleanup could potentially take a long time and be both cpu
    and disk intensive, depending on the number of session files and if
    each file needs to be read to verify the timeout value. To avoid
    overloading the server, each time filesession_cleanup is called it
    will run for a maximum of \var{session_cleanup_time_limit} seconds.
    Each cleanup call will resume from where the previous call left off
    so all session files will eventually be checked.

    Setting \var{session_cleanup_time_limit} to 0 will disable this 
    feature and filesession_cleanup will run to completion each time it
    is called.

  \item
    \var{PythonOption session_grace_period [value]}
    Integer value in seconds. Default is 240 seconds. This value is added
    to the session timeout in determining if a session file should be 
    deleted.
 
    There is a small chance that a the cleanup for a given session file
    may occur at the exact time that the session is being accessed by
    another request. It is possible under certain circumstances for that
    session file to be saved in the other request only to be immediately 
    deleted by the cleanup. To avoid this race condition, a session is
    allowed a \var{grace_period} before it is considered for deletion by
    the cleanup.  As long as the grace_period is longer that the time it
    takes to complete the request (which should normally be less than 1
    second), the session will not be mistakenly deleted by the cleanup.

    The default value should be sufficient for most applications.
  \end{itemize}

\end{classdesc}

\begin{classdesc}{MemorySession}{req, \optional{, sid, secret, timeout, lock}}

  This class provides session storage using a global dictionary. This
  class provides by far the best performance, but cannot be used in a
  multi-process configuration, and also consumes memory for every
  active session.

  Note that using this class directly is not cross-platform. For best
  compatibility across platforms, always use the \function{Session()}
  function to create sessions.

\end{classdesc}

\subsection{Examples\label{pyapi-sess-example}}
The following example demonstrates a simple hit counter.

    \begin{verbatim}

from mod_python import Session

def handler(req):
    session = Session.Session(req)

    try:
        session['hits'] += 1
    except:
        session['hits'] = 1

    session.save()

    req.content_type = 'text/plain'
    req.write('Hits: %d\n' % session['hits'])
    return apache.OK 
    \end{verbatim}

\section{\module{psp} -- Python Server Pages\label{pyapi-psp}}
\declaremodule[psp]{extension}{psp}
\modulesynopsis{Python Server Pages}
\moduleauthor{Gregory Trubetskoy}{grisha@apache.org}

The \module{psp} module provides a way to convert text documents
(including, but not limited to HTML documents) containing Python code
embedded in special brackets into pure Python code suitable for
execution within a mod_python handler, thereby providing a versatile
mechanism for delivering dynamic content in a style similar to ASP,
JSP and others.

The parser used by \module{psp} is written in C (generated using flex)
and is therefore very fast.

\emph{See \ref{hand-psp} ``PSP Handler'' for additional PSP
information.}

Inside the document, Python \dfn{code} needs to be surrounded by
\samp{<\%} and \samp{\%>}. Python \dfn{expressions} are enclosed in
\samp{<\%=} and \samp{\%>}. A \dfn{directive} can be enclosed in
\samp{<\%@} and \samp{\%>}. A comment (which will never be part of
the resulting code) can be enclosed in \samp{<\%--} and \samp{--\%>}

Here is a primitive PSP page that demonstrated use of both code and
expression embedded in an HTML document:

\begin{verbatim}
  <html>
  <%
  import time
  %>
  Hello world, the time is: <%=time.strftime("%Y-%m-%d, %H:%M:%S")%>
  </html>
\end{verbatim}

Internally, the PSP parser would translate the above page into the
following Python code:

\begin{verbatim}
  req.write("""<html>
  """)
  import time
  req.write("""
  Hello world, the time is: """); req.write(str(time.strftime("%Y-%m-%d, %H:%M:%S"))); req.write("""
  </html>
  """)
\end{verbatim}

This code, when executed inside a handler would result in a page
displaying words \samp{Hello world, the time is: } followed by current time.

Python code can be used to output parts of the page conditionally or
in loops. Blocks are denoted from within Python code by
indentation. The last indentation in Python code (even if it is a
comment) will persist through the document until either end of
document or more Python code.

Here is an example:
\begin{verbatim}
  <html>
  <%
  for n in range(3):
      # This indent will persist
  %>
  <p>This paragraph will be 
  repeated 3 times.</p>
  <%
  # This line will cause the block to end
  %>
  This line will only be shown once.<br>
  </html>
\end{verbatim}

The above will be internally translated to the following Python code:

\begin{verbatim}
  req.write("""<html>
  """)
  for n in range(3):
      # This indent will persist
      req.write("""
  <p>This paragraph will be
  repeated 3 times.</p>
  """)
  # This line will cause the block to end
  req.write("""
  This line will only be shown once.<br>
  </html>
  """)
\end{verbatim}

The parser is also smart enough to figure out the indent if the last
line of Python ends with \samp{:} (colon). Considering this, and that the
indent is reset when a newline is encountered inside \samp{<\% \%>}, the
above page can be written as:

\begin{verbatim}
  <html>
  <%
  for n in range(3):
  %>
  <p>This paragraph will be 
  repeated 3 times.</p>
  <%
  %>
  This line will only be shown once.<br>
  </html>
\end{verbatim}

However, the above code can be confusing, thus having descriptive
comments denoting blocks is highly recommended as a good practice.

The only directive supported at this time is \code{include}, here is
how it can be used:

\begin{verbatim}
<%@ include file="/file/to/include"%>
\end{verbatim}

If the \function{parse()} function was called with the \var{dir}
argument, then the file can be specified as a relative path, otherwise
it has to be absolute.

\begin{classdesc}{PSP}{req, \optional{, filename, string, vars}}
  This class represents a PSP object.

  \var{req} is a request object; \var{filename} and \var{string} are
  optional keyword arguments which indicate the source of the PSP
  code. Only one of these can be specified. If neither is specified,
  \code{req.filename} is used as \var{filename}.

  \var{vars} is a dictionary of global variables. Vars passed in the
  \method{run()} method will override vars passed in here.

  This class is used internally by the PSP handler, but can also be
  used as a general purpose templating tool.

  When a file is used as the source, the code object resulting from
  the specified file is stored in a memory cache keyed on file name
  and file modification time. The cache is global to the Python
  interpreter. Therefore, unless the file modification time changes,
  the file is parsed and resulting code is compiled only once per
  interpreter.

  The cache is limited to 512 pages, which depending on the size of
  the pages could potentially occupy a significant amount of
  memory. If memory is of concern, then you can switch to dbm file
  caching. Our simple tests showed only 20\% slower performance using
  bsd db. You will need to check which implementation \module{anydbm}
  defaults to on your system as some dbm libraries impose a limit on
  the size of the entry making them unsuitable. Dbm caching can be
  enabled via \code{PSPDbmCache} Python option, e.g.:

\begin{verbatim}
PythonOption PSPDbmCache ``/tmp/pspcache.dbm''
\end{verbatim}
  Note that the dbm cache file is not deleted when the server
  restarts.

  Unlike with files, the code objects resulting from a string are
  cached in memory only. There is no option to cache in a dbm file at
  this time.

  \begin{methoddesc}[PSP]{run}{\optional{vars}}
    This method will execute the code (produced at object
    initialization time by parsing and compiling the PSP
    source). Optional argument \var{vars} is a dictionary keyed by
    strings that will be passed in as global variables.

    Additionally, the PSP code will be given global variables
    \code{req}, \code{psp}, \code{session} and \code{form}. A session
    will be created and assigned to \code{session} variable only if
    \code{session} is referenced in the code (the PSP handler examines
    \code{co_names} of the code object to make that
    determination). Remember that a mere mention of \code{session}
    will generate cookies and turn on session locking, which may or
    may not be what you want. Similarly, a mod_python
    \class{FieldStorage} object will be instantiated if \code{form} is
    referenced in the code.

    The object passed in \code{psp} is an instance of
    \class{PSPInstance}.

  \end{methoddesc}

  \begin{methoddesc}[PSP]{display_code}{}
    Returns an HTML-formatted string representing a side-by-side
    listing of the original PSP code and resulting Python code
    produced by the PSP parser. 
  \end{methoddesc}

  Here is an example of how \class{PSP} can be used as a templating
  mechanism:
  
  The template file:
  \begin{verbatim}
<html>
  <!-- This is a simple psp template called template.html -->
  <h1>Hello, <%=what%>!</h1>
</html>
  \end{verbatim}
  The handler code:
  \begin{verbatim}
from mod_python import apache, psp

def handler(req):
    template = psp.PSP(req, filename='template.html')
    template.run({'what':'world'})
    return apache.OK
  \end{verbatim}

\end{classdesc}

\begin{classdesc}{PSPInstance}{}
  An object of this class is passed as a global variable \code{psp} to
  the PSP code. Objects of this class are instantiated internally and
  the interface to \method{__init__} is purposely undocumented.

  \begin{methoddesc}[PSPInstance]{set_error_page}{filename}
    Used to set a psp page to be processed when an exception
    occurs. If the path is absolute, it will be appended to document
    root, otherwise the file is assumed to exist in the same directory
    as the current page. The error page will receive one additional
    variable, \code{exception}, which is a 3-tuple returned by
    \code{sys.exc_info()}.
  \end{methoddesc}

  \begin{methoddesc}[PSPInstance]{apply_data}{object\optional{, **kw}}
    This method will call the callable object \var{object}, passing form
    data as keyword arguments, and return the result.
  \end{methoddesc}

  \begin{methoddesc}[PSPInstance]{redirect}{location\optional{, permanent=0}}
    This method will redirect the browser to location
    \var{location}. If \var{permanent} is true, then
    \constant{MOVED_PERMANENTLY} will be sent (as opposed to
    \constant{MOVED_TEMPORARILY}).

    \begin{notice}
      Redirection can only happen before any data is sent to the
      client, therefore the Python code block calling this method must
      be at the very beginning of the page. Otherwise an
      \exception{IOError} exception will be raised.
    \end{notice}

    Example:
    \begin{verbatim}
<%

# note that the '<' above is the first byte of the page!
psp.redirect('http://www.modpython.org')
%>
    \end{verbatim}
  \end{methoddesc}

\end{classdesc}

Additionally, the \module{psp} module provides the following low level
functions:

\begin{funcdesc}{parse}{filename\optional{, dir}}

  This function will open file named \var{filename}, read and parse its
  content and return a string of resulting Python code.

  If \var{dir} is specified, then the ultimate filename to be parsed
  is constructed by concatenating \var{dir} and \var{filename}, and
  the argument to \code{include} directive can be specified as a
  relative path. (Note that this is a simple concatenation, no path
  separator will be inserted if \var{dir} does not end with one).
\end{funcdesc}

\begin{funcdesc}{parsestring}{string}

  This function will parse contents of \var{string} and return a string
  of resulting Python code.

\end{funcdesc}
