Mercurial > hg > FileServer
annotate 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 |
rev | line source |
---|---|
0 | 1 #!/usr/bin/env python |
2 | |
3 """ | |
4 WSGI app for FileServer | |
5 | |
6 Reference: | |
7 - http://docs.webob.org/en/latest/file-example.html | |
8 """ | |
9 | |
10 import mimetypes | |
1 | 11 import optparse |
0 | 12 import os |
1 | 13 import sys |
0 | 14 from webob import Request, Response, exc |
1 | 15 from wsgiref.simple_server import make_server |
16 | |
20 | 17 __all__ = ['get_mimetype', 'file_response', 'FileApp', 'DirectoryServer', 'main'] |
0 | 18 |
26
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
19 ### classes for iterating over files |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
20 |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
21 class FileIterable(object): |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
22 def __init__(self, filename): |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
23 self.filename = filename |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
24 def __iter__(self): |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
25 return FileIterator(self.filename) |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
26 class FileIterator(object): |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
27 def __init__(self, filename, chunk_size=4096): |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
28 self.filename = filename |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
29 self.chunk_size = chunk_size |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
30 self.fileobj = open(self.filename, 'rb') |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
31 def __iter__(self): |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
32 return self |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
33 def next(self): |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
34 chunk = self.fileobj.read(self.chunk_size) |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
35 if not chunk: |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
36 raise StopIteration |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
37 return chunk |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
38 __next__ = next # py3 compat |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
39 |
0 | 40 def get_mimetype(filename): |
41 type, encoding = mimetypes.guess_type(filename) | |
42 # We'll ignore encoding, even though we shouldn't really | |
43 return type or 'application/octet-stream' | |
44 | |
45 def file_response(filename): | |
20 | 46 """return a webob response object appropriate to a file name""" |
26
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
47 res = Response(content_type=get_mimetype(filename), |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
48 conditional_response=True) |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
49 res.app_iter = FileIterable(filename) |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
50 res.content_length = os.path.getsize(filename) |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
51 res.last_modified = os.path.getmtime(filename) |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
52 res.etag = '%s-%s-%s' % (os.path.getmtime(filename), |
395c6744bcd9
upgrading with suggestions from http://docs.webob.org/en/latest/file-example.html
Jeff Hammel <jhammel@mozilla.com>
parents:
24
diff
changeset
|
53 os.path.getsize(filename), hash(filename)) |
0 | 54 return res |
55 | |
56 class FileApp(object): | |
57 """ | |
58 serve static files | |
59 """ | |
60 | |
61 def __init__(self, filename): | |
62 self.filename = filename | |
63 | |
64 def __call__(self, environ, start_response): | |
65 res = file_response(self.filename) | |
66 return res(environ, start_response) | |
67 | |
68 class DirectoryServer(object): | |
69 | |
24 | 70 def __init__(self, directory, sort=True): |
0 | 71 assert os.path.exists(directory), "'%s' does not exist" % directory |
72 assert os.path.isdir(directory), "'%s' is not a directory" % directory | |
2
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
73 self.directory = self.normpath(directory) |
24 | 74 self.sort = sort |
0 | 75 |
76 @staticmethod | |
77 def normpath(path): | |
78 return os.path.normcase(os.path.abspath(path)) | |
79 | |
17 | 80 def check_path(self, path): |
81 """ | |
82 if under the root directory, returns the full path | |
83 otherwise, returns None | |
84 """ | |
85 path = self.normpath(path) | |
86 if path == self.directory or path.startswith(self.directory + os.path.sep): | |
87 return path | |
88 | |
2
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
89 def index(self, directory): |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
90 """ |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
91 generate a directory listing for a given directory |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
92 """ |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
93 parts = ['<html><head><title>Simple Index</title></head><body>'] |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
94 listings = os.listdir(directory) |
24 | 95 if self.sort: |
96 listings.sort() | |
2
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
97 listings = [(os.path.isdir(os.path.join(directory, entry)) and entry + '/' or entry, entry) |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
98 for entry in listings] |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
99 for link, entry in listings: |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
100 parts.append('<a href="%s">%s</a><br/>' % (link, entry)) |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
101 parts.append('</body></html>') |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
102 return '\n'.join(parts) |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
103 |
0 | 104 def __call__(self, environ, start_response): |
105 request = Request(environ) | |
106 # TODO method_not_allowed: Allow: GET, HEAD | |
107 path_info = request.path_info | |
108 if not path_info: | |
13 | 109 response = exc.HTTPMovedPermanently(add_slash=True) |
110 return response(environ, start_response) | |
17 | 111 full = self.check_path(os.path.join(self.directory, path_info.strip('/'))) |
2
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
112 |
17 | 113 if full is None: |
0 | 114 # Out of bounds |
115 return exc.HTTPNotFound()(environ, start_response) | |
116 if not os.path.exists(full): | |
117 return exc.HTTPNotFound()(environ, start_response) | |
118 | |
119 if os.path.isdir(full): | |
120 # serve directory index | |
121 if not path_info.endswith('/'): | |
12 | 122 response = exc.HTTPMovedPermanently(add_slash=True) |
123 return response(environ, start_response) | |
0 | 124 index = self.index(full) |
125 response = Response(index, content_type='text/html') | |
126 return response(environ, start_response) | |
127 | |
128 # serve file | |
129 if path_info.endswith('/'): | |
130 # we create the `full` filename above by stripping off | |
131 # '/' from both sides; so we correct here | |
132 return exc.HTTPNotFound()(environ, start_response) | |
133 response = file_response(full) | |
134 return response(environ, start_response) | |
135 | |
1 | 136 def main(args=sys.argv[1:]): |
137 | |
138 # parse command line arguments | |
139 usage = '%prog [options] directory' | |
140 class PlainDescriptionFormatter(optparse.IndentedHelpFormatter): | |
141 """description formatter""" | |
142 def format_description(self, description): | |
143 if description: | |
144 return description + '\n' | |
145 else: | |
146 return '' | |
147 parser = optparse.OptionParser(usage=usage, description=__doc__, formatter=PlainDescriptionFormatter()) | |
148 parser.add_option('-p', '--port', dest='port', | |
149 type='int', default=9999, | |
150 help='port [DEFAULT: %default]') | |
151 parser.add_option('-H', '--host', dest='host', default='0.0.0.0', | |
152 help='host [DEFAULT: %default]') | |
153 options, args = parser.parse_args(args) | |
154 | |
155 # get the directory | |
156 if not len(args) == 1: | |
157 parser.print_help() | |
158 sys.exit(1) | |
159 directory = args[0] | |
160 if not os.path.exists(directory): | |
161 parser.error("'%s' not found" % directory) | |
162 if not os.path.isdir(directory): | |
163 parser.error("'%s' not a directory" % directory) | |
164 | |
165 # serve | |
166 app = DirectoryServer(directory) | |
167 try: | |
168 print 'http://%s:%s/' % (options.host, options.port) | |
169 make_server(options.host, options.port, app).serve_forever() | |
170 except KeyboardInterrupt, ki: | |
171 print "Cio, baby!" | |
172 except BaseException, e: | |
173 sys.exit("Problem initializing server: %s" % e) | |
174 | |
0 | 175 if __name__ == '__main__': |
1 | 176 main() |