[mod_python] req.sendfile() problem

Jim Gallacher jpg at jgassociates.ca
Tue Aug 8 10:35:32 EDT 2006

Thomas J. Schirripa wrote:
> Thanks a lot guys, the problem is fixed. I feel so stupid because it ended up being a naming problem - I thought the path looked okay, and I automatically assumed the name wasn't a problem because I would have thought the IOError message would have said something along the lines of "cannot find file". Anyways, I actually had a question about handling the exception because I did try doing that.
> I had req.sendfile() in a try/except block, but in order to to send the error message to the browser....
> Here's what I did...
> def handler(req):
> 	fields = util.FieldStorage(req)
> 	filename = os.path.basename(fields["filename"])
> 	directory = os.path.dirname(fields["filename"])
> 	req.headers_out["Content-Disposition"] = "attachment; filename=%s" % filename
> 	req.content_type = "text/plain"
> 	try:
> 		req.sendfile("%s/%s" % (directory, filename))
> 	except IOError, e:
> 		req.content_type = "text/html"
> 		req.write("Raised exception reads:\n<br>%s" % str(e))
> 		return apache.OK
> 	return apache.OK
> Here's what happened:
> instead of the IOError displaying in the browser, the file downloaded and had the req.write() message in it:
> "Raised exception reads:
> <br>Could not stat file for reading"
> I thought I read somewhere you can't change the content type after it has been set (a limitation of http -  in fact, this is why I have a seperate sendFile handler... so I can set the content type properly), but I didn't think this would be a problem. Is there a way to get the message to display in the browser instead of sending over an html file with the message?

You can change the content-type, or any other response headers anytime
you want, up to the first call to req.write or req.sendfile. That first
call will cause the headers to be sent before the response body, so
changing the headers from that point on will have no effect. This is a
restriction imposed by HTTP, just as you surmise.


More information about the Mod_python mailing list