-
Notifications
You must be signed in to change notification settings - Fork 0
/
python_HTTP_server.py
51 lines (36 loc) · 1.39 KB
/
python_HTTP_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#! /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()