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