[mod_python] Capturing PSP output

Graham Dumpleton grahamd at dscpl.com.au
Tue May 31 21:19:49 EDT 2005


Only just got the chance to revisit this. Here is an alternate bit of
code which avoids having to munge PSP code. This only works for
where PSP code is stored in a file. It bypasses any caching mechanism
present in the PSP class, but you could add your own if need be. It
also replaces the request object entirely with a dummy object purely
for the purposes of collecting output.

from mod_python import apache
from mod_python import _psp
  
import os
import StringIO

def _psp_to_str(filename,vars={}):
  directory,file = os.path.split(filename)

  code = _psp.parse(file,directory+'/')

  class _MPStringIO(StringIO.StringIO):
    def write(self,string,flush=1):
      StringIO.StringIO.write(self,string)

  vars["req"] = _MPStringIO()

  exec code in vars

  return vars["req"].getvalue()

def handler(req):
  directory = os.path.dirname(__file__)
  filename = os.path.join(directory,"_sample.psp")
  content = _psp_to_str(filename)

  req.content_type = "text/html"
  req.send_http_header()
  req.write(content)

  return apache.OK



Graham Dumpleton wrote ..
> 
> On 31/05/2005, at 2:19 AM, Joshua Ginsberg wrote:
> 
> > Hello --
> >
> > I'm trying to do something a little unorthodox... I didn't know if 
> > anybody had tried it before... Within a PSP page, I want to run 
> > another PSP page and capture the output to a string.
> >
> > To do a little testing, I wrote the following PSP page:
> >
> > <%
> >
> > def sAppend(self, thestring):
> >     if '__s__' not in dir(self):
> >         self.__s__ = ''
> >     self.__s__ += str(thestring)
> >
> > oldReqWrite = req.write
> >
> > req.write = sAppend
> 
> This is a bit confusing. Your method accepts a "self" parameter as if 
> it is a
> method of a class when it isn't. Just because you replace an existing 
> instance
> method will not turn your one into one.
> 
> The result is that the string to be output is being passed as self and
> string
> doesn't have a "__s__" member.
> 
> There are other problems with using "__s__" as well but rather than go
> into it,
> you should just look at:
> 
>    http://www.modpython.org/pipermail/mod_python/2005-May/018134.html
> 
> That code could probably still be cleaned up a bit perhaps as certain 
> things
> don't need to be done, also not sure why other things are being done 
> either.
> If I get a chance later I'll see if I can come up with a more 
> streamlined
> version.
> 
> BTW, did you want to actually reference the original "req" object for 
> any
> data. The example referenced obviously doesn't allow this as it 
> completely
> replaces the "req" object with a StringIO object.
> 
> Graham
> 
> _______________________________________________
> Mod_python mailing list
> Mod_python at modpython.org
> http://mailman.modpython.org/mailman/listinfo/mod_python


More information about the Mod_python mailing list