changeset 26:395c6744bcd9

upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
author Jeff Hammel <jhammel@mozilla.com>
date Mon, 05 Mar 2012 13:15:45 -0800
parents f1f53fa1e851
children 41bd126ab77d
files fileserver/web.py
diffstat 1 files changed, 28 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/fileserver/web.py	Fri Mar 02 12:50:52 2012 -0800
+++ b/fileserver/web.py	Mon Mar 05 13:15:45 2012 -0800
@@ -16,6 +16,27 @@
 
 __all__ = ['get_mimetype', 'file_response', 'FileApp', 'DirectoryServer', 'main']
 
+### classes for iterating over files
+
+class FileIterable(object):
+    def __init__(self, filename):
+        self.filename = filename
+    def __iter__(self):
+        return FileIterator(self.filename)
+class FileIterator(object):
+    def __init__(self, filename, chunk_size=4096):
+        self.filename = filename
+        self.chunk_size = chunk_size
+        self.fileobj = open(self.filename, 'rb')
+    def __iter__(self):
+        return self
+    def next(self):
+        chunk = self.fileobj.read(self.chunk_size)
+        if not chunk:
+            raise StopIteration
+        return chunk
+    __next__ = next # py3 compat
+
 def get_mimetype(filename):
     type, encoding = mimetypes.guess_type(filename)
      # We'll ignore encoding, even though we shouldn't really
@@ -23,8 +44,13 @@
 
 def file_response(filename):
     """return a webob response object appropriate to a file name"""
-    res = Response(content_type=get_mimetype(filename))
-    res.body = open(filename, 'rb').read()
+    res = Response(content_type=get_mimetype(filename),
+                   conditional_response=True)
+    res.app_iter = FileIterable(filename)
+    res.content_length = os.path.getsize(filename)
+    res.last_modified = os.path.getmtime(filename)
+    res.etag = '%s-%s-%s' % (os.path.getmtime(filename),
+                             os.path.getsize(filename), hash(filename))
     return res
 
 class FileApp(object):