6.2 Using Python Code

The extensions to mod_python to allow Python code to be used in conjunction with SSI introduces the new SSI directive called 'python'. This directive can be used in two forms, these being 'eval' and 'exec' modes. In the case of 'eval', a Python expression is used and it is the result of that expression which is substituted in place into the page.

<!--#python eval="10*'HELLO '" -->
<!--#python eval="len('HELLO')" -->

Where the result of the expression is not a string, the value will be automatically converted to a string by applying str() to the value.

In the case of 'exec' a block of Python code may be included. For any output from this code to appear in the page, it must be written back explicitly as being part of the response. As SSI are processed by an Apache output filter, this is done by using an instance of the mod_python filter object which is pushed into the global data set available to the code.

<!--#python exec="
filter.write(10*'HELLO ')
filter.write(str(len('HELLO')))
" -->

Any Python code within the 'exec' block must have a zero first level indent. You cannot start the code block with an arbitrary level of indent such that it lines up with any indenting used for surrounding HTML elements.

Although the mod_python filter object is not a true file object, that it provides the write() method is sufficient to allow the print statement to be used on it directly. This will avoid the need to explicitly convert non string objects to a string before being output.

<!--#python exec="
print >> filter, len('HELLO')
" -->