[mod_python] CGI to mod_python -- what's the best way?

Victor Muslin victor at prodigy.net
Sun Apr 8 17:38:31 EST 2001

Sorry for a long message, but this requires a bit of explanation. I 
appreciate your patience in advance.

I have a bunch of python legacy code that used to be part of a large 
CGI-based system. This code simply used print statements to output HTML as 

def foo():
         print 'html1'
         print 'html2'

Now I want to convert CGI to mod_python, but I would like to re-use the 
legacy code with as little re-writing as possible (obviously the legacy 
code is a lot lengthier and more complicated than the example above). I am 
using the publisher module, which requires my code to return a string 
containing all of the HTML. So I thought I would be clever and do something 
like this:

import sys, cStringIO
def handler(req):
         out =  sys.stdout = StringIO()
         return out

This works great as long as the second request does not arrive before the 
first one is done. Otherwise, the output gets screwed up. Since "out" is a 
local variable, each request has its own instance, but sys.stdout is a 
global. When the second request arrives, sys.stdout gets reassigned and the 
rest of the output produced by print statements in the foo() function goes 
to the new StringIO object. For example, if the second request arrives and 
gets executed between the two print statements of the first request, then 
the first request's output could be  'html1\n' and the second request's 
output could be 'html2\nhtml1\nhtml2\n'.

Has anyone dealt with such a situation? Any clever suggestion would be 
appreciated as I hate to have to go into all the legacy code and change it 
to something like this:

def foo():
         out = 'html1\n'
         out = out + 'html2\n'
         return out

def handler(req):
         return foo()

Thanks in advance.
Victor Muslin      The power of accurate observation is frequently called
                          cynicism by those who don't have it.
                                       - George Bernard Shaw
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mailman.modpython.org/pipermail/mod_python/attachments/20010408/b9ac82b3/attachment-0003.htm

More information about the Mod_python mailing list