[mod_python] feature request: psp templating returns html codeto calling script, not to browser.

Graham Dumpleton grahamd at dscpl.com.au
Thu May 19 01:52:40 EDT 2005


Wouter van Marle wrote ..
> def get_source(filename):
>     dir, fname = os.path.split(filename)
>     dir += "/"
>     pycode = _psp.parse(fname, dir).splitlines()
>     pycode = [s.rstrip() for s in pycode]
>     for line in pycode:
>         left = line.replace("\t", " "*4)
>         result += left+"\n"
>     return result

This may only work for an indenting style where tabs are used. At least
the substitution of tabs with 4 spaces looks dangerous to me in that it
could screen up indenting of code. You would also be changing tabs
that may be present in literal strings. Why did you feel you needed to
do these changes.

> def get_html(filename, vars={}):
>     code = get_source(filename)
>     lines = code.splitlines()
>     code = 'html = ""\n'
>     for l in lines:
>         l = l.replace("req.write(", "html +=").replace(",0)", "")
>         code += l+"\n"
>     global_scope = globals().copy()
>     global_scope.update(vars)
>     html = ""
>     l = locals()
>     try:
>         exec code in global_scope, l
>     except:
>         et, ev, etb = sys.exc_info()
>         raise et, ev, etb
>     return l["html"]

Actually modifying the source code seems a bit messy to me. You could
still use the "req" wrapper class hack I suggested before, or if you know
the PSP page never actually references the "req" object explicitly, you
could pass an instance of StringIO into it and call it "req" and it should just
work. This would avoid having to pass in locals(). For the purposes of
what you are doing, there is probably no point even copying globals as
it may not give you anything you need anyway. You could almost just
use "exec code in vars".

def get_html(filename, vars={}):
     code = get_source(filename)
     vars = vars.copy()
     vars["req"] = StringIO.StringIO()
     try:
         exec code in vars
     except:
         et, ev, etb = sys.exc_info()
         raise et, ev, etb
     return vars["req"].getvalue()


Graham


More information about the Mod_python mailing list