Mercurial > hg > FileServer
diff fileserver/web.py @ 0:8d31e36f084e
initial stubbing
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Wed, 29 Feb 2012 13:09:11 -0800 |
parents | |
children | 89d4f742ed1a |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/fileserver/web.py Wed Feb 29 13:09:11 2012 -0800 @@ -0,0 +1,82 @@ +#!/usr/bin/env python + +""" +WSGI app for FileServer + +Reference: +- http://docs.webob.org/en/latest/file-example.html +""" + +import mimetypes +import os +from webob import Request, Response, exc + +def get_mimetype(filename): + type, encoding = mimetypes.guess_type(filename) + # We'll ignore encoding, even though we shouldn't really + return type or 'application/octet-stream' + +def file_response(filename): + res = Response(content_type=get_mimetype(filename)) + res.body = open(filename, 'rb').read() + return res + +class FileApp(object): + """ + serve static files + """ + + def __init__(self, filename): + self.filename = filename + + def __call__(self, environ, start_response): + res = file_response(self.filename) + return res(environ, start_response) + +class DirectoryServer(object): + + def __init__(self, directory): + assert os.path.exists(directory), "'%s' does not exist" % directory + assert os.path.isdir(directory), "'%s' is not a directory" % directory + self.directory = directory + + @staticmethod + def normpath(path): + return os.path.normcase(os.path.abspath(path)) + + def __call__(self, environ, start_response): + request = Request(environ) + # TODO method_not_allowed: Allow: GET, HEAD + path_info = request.path_info + if not path_info: + pass # self.add slash + full = self.normpath(os.path.join(self.directory, path_info.strip('/'))) + if not full.startswith(self.directory): + # Out of bounds + return exc.HTTPNotFound()(environ, start_response) + if not os.path.exists(full): + return exc.HTTPNotFound()(environ, start_response) + + if os.path.isdir(full): + # serve directory index + if not path_info.endswith('/'): + return self.add_slash(environ, start_response) + index = self.index(full) + response_headers = [('Content-Type', 'text/html'), + ('Content-Length', str(len(index)))] + response = Response(index, content_type='text/html') + return response(environ, start_response) + + # serve file + if path_info.endswith('/'): + # we create the `full` filename above by stripping off + # '/' from both sides; so we correct here + return exc.HTTPNotFound()(environ, start_response) + response = file_response(full) + return response(environ, start_response) + +if __name__ == '__main__': + from wsgiref import simple_server + app = Handler() + server = simple_server.make_server(host='0.0.0.0', port=8080, app=app) + server.serve_forever()