[Twisted-Python] Serving a binary files from disk, outside folders for static content

Christopher Armstrong radix at twistedmatrix.com
Thu Feb 27 17:46:19 EST 2003


On Thu, Feb 27, 2003 at 10:59:26PM +0100, Thomas Weholt wrote:

> I need to serve a binary file from disk, not available in the normal
> folder for static content. In my code so far I've done something
> like this in the render-method :
>
> request.setContentType( .... content-type set based on extension of
> file to serve )
>
> f = open(somefile)
> while 1:
>     d = f.read(2048) # what's the correct size to read
>     if not d:
>         break
>     request.write(d)
> request.finish()
> return

zow! You should be using static.File. Just return
static.File('/path/to/binary.file') from your getChild, or putChild it
there in the first place. It will figure out the mime type by looking
it up in your mime database (/etc/mime.types), and if it's not found
in there, there's a dict of basic mime types that's hard-coded in, so
there's a good chance you won't have to set the mime-type. If you do,
you can just pass the defaultType parameter to the constructor, i.e.,
static.File('/path/foo', defaultType='application/x-octet-stream') (or
whatever the type is).

static.File is much better suited to the purpose because it's already
written :), and it doesn't block (well, it does a better job at
not-blocking, anyway), which your snippet does.

> It seem to return the data OK, it's visible in the browser, but
> exceptions are raised in the server. How do I close this connection
> the right way? Should this be used with deferred or something like
> that? The files can be huge in size.

The exceptions were probably raised because you didn't return anything
meaningful from render -- if you're going to be dealing with the
request directly (calling .write and .finish on it), then you need to
return server.NOT_DONE_YET (assuming `server' was imported with 
`from twisted.web import server'). For future reference, please show
us your tracebacks.


> PS! From recent postings in this list is seems as if Twisted doesn't
> support compression of content, using gzip etc. Is this true? This
> would speed up things considerably. I implemented this in my
> previous webserver-project using BaseHTTPServer and on big files the
> increase in speed was impressive. Compressing HTML/Plain text/XML
> etc., just files known to be based in plain text, would be a great
> start.

Patches accepted >:)

-- 
 Twisted | Christopher Armstrong: International Man of Twistery
  Radix  |          Release Manager,  Twisted Project
---------+     http://twistedmatrix.com/users/radix.twistd/




More information about the Twisted-Python mailing list