[Tutor] Redirect from a CGI script
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Sat Jan 20 21:59:37 CET 2007
On Sat, 20 Jan 2007, Python wrote:
> On Sat, 2007-01-20 at 10:13 -0800, Danny Yoo wrote:
>> The last line of the program looks suspicious. If it helps, let me
>> rearrange the program that you've written to:
>>
>> ###############################################
>> print "Content-type: text/html\r\n"
>> print "Location: http://python.org/\r\n"
>> print "\r"
>> ###############################################
>>
>> The code is missing the critical '\n' that allows the web browser to
>> recognize the header.
>
> That gets supplied from the print - doesn't it?.
Hi Lloyd and Paulino,
Ah, very true. Ah ha! That's exactly the problem here. Thanks Lloyd!
What's happening is that Python's 'print' statement introduces its own
newline between the content-type header and the location header.
So the bytes that are actually being written to the server look something
like:
"Content-type: text/html\r\n\nLocation: http://python.org/\r\n\n\r\n"
which is wrong: we really want it to be:
"Content-type: text/html\r\nLocation: http://python.org/\r\n\r\n"
> sys.stdout.write(...) would need the final \n and might actually be
> clearer.
Yeah, I agree: that's exactly the right thing to use here. (Actually, the
right thing to do here is probably to use a separate client library that
handles the ugliness, raw details of the CGI protocol.)
Paulino, in any case, use sys.stdout.write() rather than the print
statement, at least when you're writing out the headers. You need the
extra control that sys.stdout.write() gives you: 'print' is introducing
newlines that, under normal circumstances, are harmless, but when we're
writing headers like this, make it easy to make the mistakes above.
Thanks again Lloyd!
More information about the Tutor
mailing list