6.4 Pre-propulating Globals

#
6.4 Pre-propulating Globals

Any Python code which appears within the page has to be compiled each time the page is accessed before it is executed. In other words, the compiled code is not cached between requests. To limit such recompilation and to avoid duplication of common code amongst many pages, it is preferable to pre-populate the global data from within a mod_python handler prior to the page being processed.

In most cases, a fixup handler would be used for this purpose. For this to work, first need to configure Apache so that it knows to call the fixup handler.

    PythonFixupHandler _handlers

The implementation of the fixup handler contained in `_handlers.py` then needs to create an instance of a Python dictionary, store that in the mod_python request object as `ssi_globals` and then populate that dictionary with any data to be available to the Python code executing within the page.

    from mod_python import apache

    import cgi, time

    def _escape(object):
        return cgi.escape(str(object))

    def _header(filter):
        print >> filter, '...'

    def _footer(filter):
        print >> filter, '...'

    def fixuphandler(req):
        req.ssi_globals = {}
        req.ssi_globals['time'] = time
        req.ssi_globals['_escape'] = _escape
        req.ssi_globals['_header'] = _header
        req.ssi_globals['_footer'] = _footer
        return apache.OK

This is most useful where it is necessary to insert common information such as headers, footers or menu panes which are dynamically generated into many pages.

    <!--#python exec="
    now = time.time()
    " -->
    <html>
    <body>
    <!--#python exec="_header(filter)" -->
    <pre>
    <!--#python eval="_escape(time.asctime(time.localtime(now)))"-->
    </pre>
    <!--#python exec="_footer(filter)" -->
    </body>
    </html>