|
| 1 | +#! /usr/bin/env python |
| 2 | + |
| 3 | +import posixpath |
| 4 | +import argparse |
| 5 | +import urllib |
| 6 | +import os |
| 7 | + |
| 8 | +from SimpleHTTPServer import SimpleHTTPRequestHandler |
| 9 | +from BaseHTTPServer import HTTPServer |
| 10 | + |
| 11 | + |
| 12 | +class RootedHTTPServer(HTTPServer): |
| 13 | + |
| 14 | + def __init__(self, base_path, *args, **kwargs): |
| 15 | + HTTPServer.__init__(self, *args, **kwargs) |
| 16 | + self.RequestHandlerClass.base_path = base_path |
| 17 | + |
| 18 | + |
| 19 | +class RootedHTTPRequestHandler(SimpleHTTPRequestHandler): |
| 20 | + |
| 21 | + def translate_path(self, path): |
| 22 | + path = posixpath.normpath(urllib.unquote(path)) |
| 23 | + words = path.split('/') |
| 24 | + words = filter(None, words) |
| 25 | + path = self.base_path |
| 26 | + for word in words: |
| 27 | + drive, word = os.path.splitdrive(word) |
| 28 | + head, word = os.path.split(word) |
| 29 | + if word in (os.curdir, os.pardir): |
| 30 | + continue |
| 31 | + path = os.path.join(path, word) |
| 32 | + return path |
| 33 | + |
| 34 | + |
| 35 | +def main(HandlerClass=RootedHTTPRequestHandler, ServerClass=RootedHTTPServer): |
| 36 | + |
| 37 | + parser = argparse.ArgumentParser() |
| 38 | + parser.add_argument('--port', '-p', default=os.getenv('PORT', 5000), type=int) |
| 39 | + parser.add_argument('--dir', '-d', default=os.getcwd(), type=str) |
| 40 | + args = parser.parse_args() |
| 41 | + |
| 42 | + server_address = ('', args.port) |
| 43 | + |
| 44 | + httpd = ServerClass(args.dir, server_address, HandlerClass) |
| 45 | + |
| 46 | + sa = httpd.socket.getsockname() |
| 47 | + print "Serving HTTP on", sa[0], "port", sa[1], "..." |
| 48 | + httpd.serve_forever() |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + main() |
0 commit comments