[mod_python] Request sendfile question

Jim Gallacher jpg at jgassociates.ca
Fri Mar 24 08:34:23 EST 2006

Ville Silventoinen wrote:
> Hi,
> is there a way to send a file using a file handle?
> I've got a file archive, which stores files in gzip format. When a 
> client downloads the file, I'd like to send the file uncompressed, 
> without creating a temporary file.
> I'm sending the file like this (bit simplified):
>     req.filename = fname
>     req.content_type = ctype
>     req.set_content_length = flen

I assume this is a typo but just in case it's not, 
req.set_content_length is a method, not an attribute.

>     fh = gzip.GzipFile(fpath, 'rb', 9)
>     block_size = 1024
>     while 1:
>         data = fh.read(block_size)
>         if not data:
>             break
>         req.write(data)
>     fh.close()
>     return apache.OK
> I've tested this with different files, it seems to work ok. I was 
> looking at the requestobject.c. Would it be easy to implement something 
> like req_sendfh in addition to req_sendfile?

It is probably possible to implement such a thing, but it wouldn't work 
for your use case.

In your example you have a GzipFile instance, which is a *file-like* 
object. This object wraps the real file object and provides the "zippy" 
behaviour. The real file handle is not exposed, and would be useless 
even if it was available since reading from it would just give you the 
compressed stream. (Correctly speaking you could use 
fh.fileobj.fileno(), but it really is not meant to be used directly). If 
you take look at gzip.py in the python lib I think you'll see what I mean.

So in short, your current solution is the correct one.


More information about the Mod_python mailing list