WebOb File-Serving Example

    Note

    Starting from 1.2b4, WebOb ships with a webob.static module which implements a 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. >>> 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:

    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. >>> print req.get_response(app)
    2. Content-Type: text/plain; charset=UTF-8
    3. Content-Length: 35
    4. This is a test. Hello test people!

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

    Now we’ll test it out: