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