Mercurial > hg > FileServer
annotate fileserver/web.py @ 21:3ce9fe38f5e1
addendum
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Wed, 29 Feb 2012 16:39:50 -0800 |
parents | 1eb5e82605a5 |
children | eb15c8321ad8 |
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 |
19 def get_mimetype(filename): | |
20 type, encoding = mimetypes.guess_type(filename) | |
21 # We'll ignore encoding, even though we shouldn't really | |
22 return type or 'application/octet-stream' | |
23 | |
24 def file_response(filename): | |
20 | 25 """return a webob response object appropriate to a file name""" |
0 | 26 res = Response(content_type=get_mimetype(filename)) |
27 res.body = open(filename, 'rb').read() | |
28 return res | |
29 | |
30 class FileApp(object): | |
31 """ | |
32 serve static files | |
33 """ | |
34 | |
35 def __init__(self, filename): | |
36 self.filename = filename | |
37 | |
38 def __call__(self, environ, start_response): | |
39 res = file_response(self.filename) | |
40 return res(environ, start_response) | |
41 | |
42 class DirectoryServer(object): | |
43 | |
44 def __init__(self, directory): | |
45 assert os.path.exists(directory), "'%s' does not exist" % directory | |
46 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
|
47 self.directory = self.normpath(directory) |
0 | 48 |
49 @staticmethod | |
50 def normpath(path): | |
51 return os.path.normcase(os.path.abspath(path)) | |
52 | |
17 | 53 def check_path(self, path): |
54 """ | |
55 if under the root directory, returns the full path | |
56 otherwise, returns None | |
57 """ | |
58 path = self.normpath(path) | |
59 if path == self.directory or path.startswith(self.directory + os.path.sep): | |
60 return path | |
61 | |
2
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
62 def index(self, directory): |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
63 """ |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
64 generate a directory listing for a given directory |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
65 """ |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
66 parts = ['<html><head><title>Simple Index</title></head><body>'] |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
67 listings = os.listdir(directory) |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
68 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
|
69 for entry in listings] |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
70 for link, entry in listings: |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
71 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
|
72 parts.append('</body></html>') |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
73 return '\n'.join(parts) |
8fb047af207a
this now actually serves things
Jeff Hammel <jhammel@mozilla.com>
parents:
1
diff
changeset
|
74 |
0 | 75 def __call__(self, environ, start_response): |
76 request = Request(environ) | |
77 # TODO method_not_allowed: Allow: GET, HEAD | |
78 path_info = request.path_info | |
79 if not path_info: | |
13 | 80 response = exc.HTTPMovedPermanently(add_slash=True) |
81 return response(environ, start_response) | |
17 | 82 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
|
83 |
17 | 84 if full is None: |
0 | 85 # Out of bounds |
86 return exc.HTTPNotFound()(environ, start_response) | |
87 if not os.path.exists(full): | |
88 return exc.HTTPNotFound()(environ, start_response) | |
89 | |
90 if os.path.isdir(full): | |
91 # serve directory index | |
92 if not path_info.endswith('/'): | |
12 | 93 response = exc.HTTPMovedPermanently(add_slash=True) |
94 return response(environ, start_response) | |
0 | 95 index = self.index(full) |
96 response = Response(index, content_type='text/html') | |
97 return response(environ, start_response) | |
98 | |
99 # serve file | |
100 if path_info.endswith('/'): | |
101 # we create the `full` filename above by stripping off | |
102 # '/' from both sides; so we correct here | |
103 return exc.HTTPNotFound()(environ, start_response) | |
104 response = file_response(full) | |
105 return response(environ, start_response) | |
106 | |
1 | 107 def main(args=sys.argv[1:]): |
108 | |
109 # parse command line arguments | |
110 usage = '%prog [options] directory' | |
111 class PlainDescriptionFormatter(optparse.IndentedHelpFormatter): | |
112 """description formatter""" | |
113 def format_description(self, description): | |
114 if description: | |
115 return description + '\n' | |
116 else: | |
117 return '' | |
118 parser = optparse.OptionParser(usage=usage, description=__doc__, formatter=PlainDescriptionFormatter()) | |
119 parser.add_option('-p', '--port', dest='port', | |
120 type='int', default=9999, | |
121 help='port [DEFAULT: %default]') | |
122 parser.add_option('-H', '--host', dest='host', default='0.0.0.0', | |
123 help='host [DEFAULT: %default]') | |
124 options, args = parser.parse_args(args) | |
125 | |
126 # get the directory | |
127 if not len(args) == 1: | |
128 parser.print_help() | |
129 sys.exit(1) | |
130 directory = args[0] | |
131 if not os.path.exists(directory): | |
132 parser.error("'%s' not found" % directory) | |
133 if not os.path.isdir(directory): | |
134 parser.error("'%s' not a directory" % directory) | |
135 | |
136 # serve | |
137 app = DirectoryServer(directory) | |
138 try: | |
139 print 'http://%s:%s/' % (options.host, options.port) | |
140 make_server(options.host, options.port, app).serve_forever() | |
141 except KeyboardInterrupt, ki: | |
142 print "Cio, baby!" | |
143 except BaseException, e: | |
144 sys.exit("Problem initializing server: %s" % e) | |
145 | |
0 | 146 if __name__ == '__main__': |
1 | 147 main() |