-
Notifications
You must be signed in to change notification settings - Fork 151
/
server.py
52 lines (38 loc) · 1.5 KB
/
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
52
#! /usr/bin/env python
import posixpath
import argparse
import urllib
import os
from http.server import SimpleHTTPRequestHandler
from http.server 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):
url_path = urllib.parse.urlparse(path).path
path = posixpath.normpath(urllib.parse.unquote(url_path))
words = [w for w in path.split('/') if w]
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 main(HandlerClass=RootedHTTPRequestHandler, ServerClass=RootedHTTPServer):
parser = argparse.ArgumentParser()
parser.add_argument('--port', '-p',
default=os.getenv('PORT', 5000),
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__':
main()