Mercurial > hg > FileServer
comparison fileserver/web.py @ 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 | eb15c8321ad8 |
children | 0edb831061f5 |
comparison
equal
deleted
inserted
replaced
25:f1f53fa1e851 | 26:395c6744bcd9 |
---|---|
14 from webob import Request, Response, exc | 14 from webob import Request, Response, exc |
15 from wsgiref.simple_server import make_server | 15 from wsgiref.simple_server import make_server |
16 | 16 |
17 __all__ = ['get_mimetype', 'file_response', 'FileApp', 'DirectoryServer', 'main'] | 17 __all__ = ['get_mimetype', 'file_response', 'FileApp', 'DirectoryServer', 'main'] |
18 | 18 |
19 ### classes for iterating over files | |
20 | |
21 class FileIterable(object): | |
22 def __init__(self, filename): | |
23 self.filename = filename | |
24 def __iter__(self): | |
25 return FileIterator(self.filename) | |
26 class FileIterator(object): | |
27 def __init__(self, filename, chunk_size=4096): | |
28 self.filename = filename | |
29 self.chunk_size = chunk_size | |
30 self.fileobj = open(self.filename, 'rb') | |
31 def __iter__(self): | |
32 return self | |
33 def next(self): | |
34 chunk = self.fileobj.read(self.chunk_size) | |
35 if not chunk: | |
36 raise StopIteration | |
37 return chunk | |
38 __next__ = next # py3 compat | |
39 | |
19 def get_mimetype(filename): | 40 def get_mimetype(filename): |
20 type, encoding = mimetypes.guess_type(filename) | 41 type, encoding = mimetypes.guess_type(filename) |
21 # We'll ignore encoding, even though we shouldn't really | 42 # We'll ignore encoding, even though we shouldn't really |
22 return type or 'application/octet-stream' | 43 return type or 'application/octet-stream' |
23 | 44 |
24 def file_response(filename): | 45 def file_response(filename): |
25 """return a webob response object appropriate to a file name""" | 46 """return a webob response object appropriate to a file name""" |
26 res = Response(content_type=get_mimetype(filename)) | 47 res = Response(content_type=get_mimetype(filename), |
27 res.body = open(filename, 'rb').read() | 48 conditional_response=True) |
49 res.app_iter = FileIterable(filename) | |
50 res.content_length = os.path.getsize(filename) | |
51 res.last_modified = os.path.getmtime(filename) | |
52 res.etag = '%s-%s-%s' % (os.path.getmtime(filename), | |
53 os.path.getsize(filename), hash(filename)) | |
28 return res | 54 return res |
29 | 55 |
30 class FileApp(object): | 56 class FileApp(object): |
31 """ | 57 """ |
32 serve static files | 58 serve static files |