-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathserver.py
executable file
·55 lines (40 loc) · 1.29 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
53
54
55
#!/usr/bin/python3
import argparse
from contextlib import contextmanager
import http.server
from pathlib import Path
import shutil
import socketserver
class Handler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header("Access-Control-Allow-Origin", "*")
super().end_headers()
def send_head(self):
if self.path.endswith(".zip"):
path = Path(self.path)
if str(path).startswith("/"):
path = Path("." + str(path)).resolve()
shutil.make_archive(path.with_suffix(""), "zip", root_dir=path.parent)
return super().send_head()
def make_parser(parser):
parser.description = "Start a server"
parser.add_argument(
"--port", action="store", type=int, default=8000, help="choose the port"
)
return parser
@contextmanager
def server(port):
httpd = socketserver.TCPServer(("", port), Handler)
try:
yield httpd
finally:
httpd.shutdown()
def main(args):
port = args.port
with server(port) as httpd:
print(f"serving from {Path(__file__).resolve().parent} at http://localhost:{port}")
httpd.serve_forever()
if __name__ == "__main__":
parser = make_parser(argparse.ArgumentParser())
args = parser.parse_args()
main(args)