-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttp_server.py
64 lines (60 loc) · 1.98 KB
/
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
52
53
54
55
56
57
58
59
60
61
62
63
64
import sys
from http.server import HTTPServer, SimpleHTTPRequestHandler
import importlib
import io
import urllib.request, urllib.parse, urllib.error
import traceback
import web_app
class RequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.client_address[0] != '127.0.0.1':
self.send_error(501, 'Only local host allowed')
return False
path, _, query = self.path.partition('?')
if path == '/':
self.do_CGI(query)
else:
return super().do_GET()
def do_CGI(self, query):
dic = self.parse_query(query)
sdout = sys.stdout
importlib.reload(web_app)
stringio = io.StringIO()
sys.stdout = stringio
try:
web_app.run(**dic)
except:
print('<pre>%s</pre>' % traceback.format_exc())
finally:
self.send_response(200)
self.send_header("Content-type", 'text/html')
self.end_headers()
self.wfile.write(stringio.getvalue().encode('utf-8'))
sys.stdout = sdout
stringio.close()
def parse_query(self, query):
dic = {}
query = urllib.parse.unquote(query)
for par in query.replace('+',' ').split('&'):
kv = par.split('=', 1)
if len(kv) == 2:
name, value = kv
if name in dic:
oldvalue = dic[name]
if isinstance(oldvalue, str):
dic[name] = [oldvalue, value]
else:
dic[name].append(value)
else:
dic[name] = value
return dic
if __name__ == '__main__':
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
server_address = ('127.0.0.1', port)
httpd = HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print("Serving HTTP on", sa[0], "port", sa[1], "...")
httpd.serve_forever()