[python-win32] Response.Write / Print

Jim Abrams Jim Abrams <jabrams@publishingresources.com>
Tue, 14 Aug 2001 13:03:17 -0400


RA> How can I override the print method to work as Response.Write in
RA> ASP?

Two different things here. First, getting the Print state to work in
ASP is tricky, here are some hints. First, you can't use the regular
print statement, and here's why. I'm not %100 sure of myself here so
if anyone seems me err, please correct.

The print statement sends data to sys.stdout by default.
However, python in ASP caches all modules, on an application level
scope, so sys.stdout is shared by every script on your website.
However, in order for the webserver to know where to send data back to
the client, it must have a unique filehandle (or some similar object)
for each page request.

Trying to set something to sys.stdout might appear to work, but
actually will break as soon as you start to get simultaneous requests.
(I actually had data from page 1 appears on page 2 when I requested
both at the same time.)

What you need to do is get some page level scope variable, stick an
object in it that maps print to Response.Write, and use the augmented
print.

Here's what I do.

from win32com.axscript.client.framework import SafeOutput
_out = SafeOutput(Response)

Then I use print >> _out, stuff

I stuck the code in an include file that gets included on every page.
Tiresome but after set up works very nicely.

RA> I really want to be able to use my scripts in multiple
RA> places,not just on the web server.

After that you can always assign sys.stdout to _out to get the right
behavior if you're not running the script from ASP.
Actually I faintly remember that if _out is None, it will go to stdout
too. But don't quote me.

RA> If this can't be done, what variable can I examine to determine
RA> where the script is being run so I know what to call? Thanks
Not sure here, I suppose you could look for the existence of Response,
Request, etc, ASP's built in objects to see if they are defined, but
that feels icky to me. Someone must know a better way. And whoever
that is, might you know how to tell the difference between IIS's main
thread of execution and other worker threads?

-- 
Jim Abrams