WebOb File-Serving Example

This document shows how you can make a static-file-serving application using WebOb. We’ll quickly build this up from minimal functionality to a high-quality file serving application.

Note

Starting from 1.2b4, WebOb ships with a webob.static module which implements a webob.static.FileApp WSGI application similar to the one described below.

This document stays as a didactic example how to serve files with WebOb, but you should consider using applications from webob.static in production.

First we’ll setup a really simple shim around our application, which we can use as we improve our application:

  1. >>> from webob import Request, Response
  2. >>> import os
  3. >>> class FileApp(object):
  4. ... def __init__(self, filename):
  5. ... self.filename = filename
  6. ... def __call__(self, environ, start_response):
  7. ... res = make_response(self.filename)
  8. ... return res(environ, start_response)
  9. >>> import mimetypes
  10. >>> def get_mimetype(filename):
  11. ... type, encoding = mimetypes.guess_type(filename)
  12. ... # We'll ignore encoding, even though we shouldn't really
  13. ... return type or 'application/octet-stream'

Now we can make different definitions of make_response. The simplest version:

  1. >>> def make_response(filename):
  2. ... res = Response(content_type=get_mimetype(filename))
  3. ... res.body = open(filename, 'rb').read()
  4. ... return res

We’ll test it out with a file test-file.txt in the WebOb doc directory, which has the following content:

  1. This is a test. Hello test people!

Let’s give it a shot:

  1. >>> fn = os.path.join(doc_dir, 'file-example-code/test-file.txt')
  2. >>> open(fn).read()
  3. 'This is a test. Hello test people!'
  4. >>> app = FileApp(fn)
  5. >>> req = Request.blank('/')
  6. >>> print req.get_response(app)
  7. 200 OK
  8. Content-Type: text/plain; charset=UTF-8
  9. Content-Length: 35
  10. This is a test. Hello test people!

Well, that worked. But it’s not a very fancy object. First, it reads everything into memory, and that’s bad. We’ll create an iterator instead:

  1. >>> class FileIterable(object):
  2. ... def __init__(self, filename):
  3. ... self.filename = filename
  4. ... def __iter__(self):
  5. ... return FileIterator(self.filename)
  6. >>> class FileIterator(object):
  7. ... chunk_size = 4096
  8. ... def __init__(self, filename):
  9. ... self.filename = filename
  10. ... self.fileobj = open(self.filename, 'rb')
  11. ... def __iter__(self):
  12. ... return self
  13. ... def next(self):
  14. ... chunk = self.fileobj.read(self.chunk_size)
  15. ... if not chunk:
  16. ... raise StopIteration
  17. ... return chunk
  18. ... __next__ = next # py3 compat
  19. >>> def make_response(filename):
  20. ... res = Response(content_type=get_mimetype(filename))
  21. ... res.app_iter = FileIterable(filename)
  22. ... res.content_length = os.path.getsize(filename)
  23. ... return res

And testing:

  1. >>> req = Request.blank('/')
  2. >>> print req.get_response(app)
  3. 200 OK
  4. Content-Type: text/plain; charset=UTF-8
  5. Content-Length: 35
  6. This is a test. Hello test people!

Well, that doesn’t look different, but lets imagine that it’s different because we know we changed some code. Now to add some basic metadata to the response:

  1. >>> def make_response(filename):
  2. ... res = Response(content_type=get_mimetype(filename),
  3. ... conditional_response=True)
  4. ... res.app_iter = FileIterable(filename)
  5. ... res.content_length = os.path.getsize(filename)
  6. ... res.last_modified = os.path.getmtime(filename)
  7. ... res.etag = '%s-%s-%s' % (os.path.getmtime(filename),
  8. ... os.path.getsize(filename), hash(filename))
  9. ... return res

Now, with conditional_response on, and with last_modified and etag set, we can do conditional requests:

  1. >>> req = Request.blank('/')
  2. >>> res = req.get_response(app)
  3. >>> print res
  4. 200 OK
  5. Content-Type: text/plain; charset=UTF-8
  6. Content-Length: 35
  7. Last-Modified: ... GMT
  8. ETag: ...-...
  9. This is a test. Hello test people!
  10. >>> req2 = Request.blank('/')
  11. >>> req2.if_none_match = res.etag
  12. >>> req2.get_response(app)
  13. <Response ... 304 Not Modified>
  14. >>> req3 = Request.blank('/')
  15. >>> req3.if_modified_since = res.last_modified
  16. >>> req3.get_response(app)
  17. <Response ... 304 Not Modified>

We can even do Range requests, but it will currently involve iterating through the file unnecessarily. When there’s a range request (and you set conditional_response=True) the application will satisfy that request. But with an arbitrary iterator the only way to do that is to run through the beginning of the iterator until you get to the chunk that the client asked for. We can do better because we can use fileobj.seek(pos) to move around the file much more efficiently.

So we’ll add an extra method, app_iter_range, that Response looks for:

  1. >>> class FileIterable(object):
  2. ... def __init__(self, filename, start=None, stop=None):
  3. ... self.filename = filename
  4. ... self.start = start
  5. ... self.stop = stop
  6. ... def __iter__(self):
  7. ... return FileIterator(self.filename, self.start, self.stop)
  8. ... def app_iter_range(self, start, stop):
  9. ... return self.__class__(self.filename, start, stop)
  10. >>> class FileIterator(object):
  11. ... chunk_size = 4096
  12. ... def __init__(self, filename, start, stop):
  13. ... self.filename = filename
  14. ... self.fileobj = open(self.filename, 'rb')
  15. ... if start:
  16. ... self.fileobj.seek(start)
  17. ... if stop is not None:
  18. ... self.length = stop - start
  19. ... else:
  20. ... self.length = None
  21. ... def __iter__(self):
  22. ... return self
  23. ... def next(self):
  24. ... if self.length is not None and self.length <= 0:
  25. ... raise StopIteration
  26. ... chunk = self.fileobj.read(self.chunk_size)
  27. ... if not chunk:
  28. ... raise StopIteration
  29. ... if self.length is not None:
  30. ... self.length -= len(chunk)
  31. ... if self.length < 0:
  32. ... # Chop off the extra:
  33. ... chunk = chunk[:self.length]
  34. ... return chunk
  35. ... __next__ = next # py3 compat

Now we’ll test it out:

  1. >>> req = Request.blank('/')
  2. >>> res = req.get_response(app)
  3. >>> req2 = Request.blank('/')
  4. >>> # Re-fetch the first 5 bytes:
  5. >>> req2.range = (0, 5)
  6. >>> res2 = req2.get_response(app)
  7. >>> res2
  8. <Response ... 206 Partial Content>
  9. >>> # Let's check it's our custom class:
  10. >>> res2.app_iter
  11. <FileIterable object at ...>
  12. >>> res2.body
  13. 'This '
  14. >>> # Now, conditional range support:
  15. >>> req3 = Request.blank('/')
  16. >>> req3.if_range = res.etag
  17. >>> req3.range = (0, 5)
  18. >>> req3.get_response(app)
  19. <Response ... 206 Partial Content>
  20. >>> req3.if_range = 'invalid-etag'
  21. >>> req3.get_response(app)
  22. <Response ... 200 OK>