Created
August 15, 2016 15:47
-
-
Save diegosorrilha/812787c01b65fde6dec870ab97212abd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ python server.py --dir ~/Documents --port 5000 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
import posixpath | |
import argparse | |
import urllib | |
import os | |
from SimpleHTTPServer import SimpleHTTPRequestHandler | |
from BaseHTTPServer import HTTPServer | |
class RootedHTTPServer(HTTPServer): | |
def __init__(self, base_path, *args, **kwargs): | |
HTTPServer.__init__(self, *args, **kwargs) | |
self.RequestHandlerClass.base_path = base_path | |
class RootedHTTPRequestHandler(SimpleHTTPRequestHandler): | |
def translate_path(self, path): | |
path = posixpath.normpath(urllib.unquote(path)) | |
words = path.split('/') | |
words = filter(None, words) | |
path = self.base_path | |
for word in words: | |
drive, word = os.path.splitdrive(word) | |
head, word = os.path.split(word) | |
if word in (os.curdir, os.pardir): | |
continue | |
path = os.path.join(path, word) | |
return path | |
def test(HandlerClass=RootedHTTPRequestHandler, ServerClass=RootedHTTPServer): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--port', '-p', default=8000, type=int) | |
parser.add_argument('--dir', '-d', default=os.getcwd(), type=str) | |
args = parser.parse_args() | |
server_address = ('', args.port) | |
httpd = ServerClass(args.dir, server_address, HandlerClass) | |
sa = httpd.socket.getsockname() | |
print "Serving HTTP on", sa[0], "port", sa[1], "..." | |
httpd.serve_forever() | |
if __name__ == '__main__': | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it works great, thank you!