[mod_python] How to get the html code in a string when using psp ?

Detmar Meurers dm at ling.ohio-state.edu
Wed Jul 18 14:19:15 EDT 2007

Hi Martin,
    I am new to the mod_python mailing list.

    I just wrote a small code that uses  the  publisher  handler and  psp. 
    The pages are correctly generated and published for the users of the
    website. My only problem is that I would like to mail a copy of the page
    to some email adress.
    How could I get the html code of the generated pages in a string ? (if
    possible, not using the obvious solution of reposting the data and
    grabbing the code through for example wget).
I asked this a while back and based on a pointer by Graham Dumpleton
to a posting by Jim Gallacher I wrote the code below which I think
does what you're looking for.


# Example code for turning psp template into html string, based on
# http://www.modpython.org/pipermail/mod_python/2006-June/021292.html

from mod_python import _psp

def psp2html(filename,vars={}):
     req = FakeRequestObject()
     vars['req'] = req
     source = _psp.parse(filename)
     code = compile(source, filename, 'exec')
     global_scope = globals().copy()
     exec code in global_scope
     return req.html()

class FakeRequestObject(object):
     def __init__(self):
          self.htmlList = []

     def write(self, value, length):

     def html(self):
	 return "".join(self.htmlList)

if __name__ == "__main__":
    print psp2html('template_file.psp',  {'var_in_psp1': 'some value' ,
                                          'var_in_psp2': 'another value'})

### end of python file

For completeness sake, the template_file.psp mentioned above looks as:

      <%= var_in_psp1 %>

      <%= var_in_psp2 %>

More information about the Mod_python mailing list