Mercurial > hg > simpypi
view simpypi/factory.py @ 16:d3efc504c0b1
more towards the type of fileserver we actually care about
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Tue, 28 Feb 2012 15:17:23 -0800 |
parents | 1cdb25cef7ee |
children | 77357c5c33c2 |
line wrap: on
line source
import os from dispatcher import Dispatcher from paste.httpexceptions import HTTPExceptionHandler from paste.urlparser import StaticURLParser from pkg_resources import resource_filename class PassthroughFileserver(object): """serve files if they exist""" def __init__(self, app, directory): self.app = app self.directory = directory self.fileserver = StaticURLParser(directory) def __call__(self, environ, start_response): path = self.path(environ['PATH_INFO'].strip('/')) if path and os.path.exists(os.path.join(self.directory, path)): return self.fileserver(environ, start_response) return self.app(environ, start_response) class NamespacedFileserver(PassthroughFileserver): def __init__(self, app, directory, namespace): PassthroughFileserver.__init__(self, app, directory) self.namespace = namespace def __call__(self, environ, start_response): path = environ['PATH_INFO'] if path == self.namespace: environ['PATH_INFO'] = '/' return self.fileserver(environ, start_response) elif path.startswith(self.namespace + '/'): environ['PATH_INFO'] = path[len(self.namespace):] return self.fileserver(environ, start_response) return self.app(environ, start_response) def factory(**app_conf): """create a webob view and wrap it in middleware""" directory = app_conf['directory'] app = Dispatcher(**app_conf) # TODO: something about serving simple_index, etc return PassthroughFileserver(app, resource_filename(__name__, 'static')) if __name__ == '__main__': import shutil import tempfile from wsgiref import simple_server port = 8080 print "http://localhost:%d/" % port tempdir = tempfile.mkdtemp() try: app = factory(directory=tempdir) server = simple_server.make_server(host='0.0.0.0', port=port, app=app) server.serve_forever() finally: shutil.rmtree(tempdir)