[mod_python] (servlet) download files with req.sendfile

Daniel Popowich dpopowich at comcast.net
Wed Jul 14 12:41:34 EDT 2004


Sharky @ Code Zone writes:
> So imagine that i don't append any HTML to the end of ths files, only
> send file or show some HTML. When i do a req.sendfile(), he overwrite my
> content_type...
> 
> You can see it in actions on: http://pytsts2.codezone.ath.cx/dwn69a
> 

There are two problems with your servlet:

 1       def prep(self):
 2          Down.prep(self)
 3          self.title = self.dwn
 4          if self.dwn == 'teste.tgz' or self.dwn == 'teste.bz2':
 5              file = '/home/sharky/virtualhosts/vhost4/html/'+self.dwn
 6              self.content_type = 'application/x-gzip'
 7              self.req.sendfile(file, 0, -1)
 8          else:
 9              self.writeln( conteudo )
10              self.writeln(self.py.setdefault(self,
11                          HTMLHighlightedPy(open(self.sourcefilename()).read())))


 1) Change line #6 to:

      self.req.content_type = 'application/x-gzip'

    Because you are calling self.req.sendfile() to return content to
    the client, the value of self.content_type will never be
    propagated to the request object.  self.content_type only
    propagates to the request object (self.req.content_type) after a
    call to self.write or self.writeln.  The curious can look at the
    code in servlet.Servlet.flush.

 2) Insert after line #7, as the last line of the IF suite:

      raise apache.SERVER_RETURN, apache.OK

    The sendfile method DOES return.  So in your case, after the call
    to prep() finishes, the call to respond() is made; that's why
    you're seeing the HTML concatenated after the file returned.

Also, as a general note, I would avoid generating output inside calls
to prep (your ELSE suite).  If subclassing HTMLPage, put HTML output
inside calls to write_content.

Cheers,

Daniel



More information about the Mod_python mailing list