-
Notifications
You must be signed in to change notification settings - Fork 19
/
httpinput.py
79 lines (73 loc) · 2.55 KB
/
httpinput.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Copyright (C) John Leach <[email protected]>
# Released under the terms of the GNU General Public License version 3
import BaseHTTPServer
import cgi
import thread
import collections
import itertools
PageInfo = collections.namedtuple('PageInfo', ['title', 'buttons', 'callback'])
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
bstr = ""
bstyle = ""
info = self.server.page_info
rows = len(info.buttons)
bstyle += "button { font-size: 30px; height: %d%%; margin: 0; }" % (int(90 / (rows - 0.1)))
for r in info.buttons:
bstr += '<p>'
for name in r:
if '#' in name:
(name, style) = name.split('#', 1)
else:
style = ''
bstr += "<button type='submit' name='%s'>%s</button>" % (name, name)
bstyle += "button[name=%s] { width: %d%% ; %s } " % (name, int(95 / (len(r) - 0.05)), style)
bstr += '</p>'
self.wfile.write("""<html>
<head>
<title>%(title)s</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
</head>
<body>
<style>%(bstyle)s</style>
<form method='post'>
%(bstr)s
</form>
<script>
$(function() {
$("button").click(function() {
$("button").attr("disabled", true);
$.ajax({
type: "POST",
url: $(this).attr("name"),
timeout: 3000,
error: function(data) {
$("button").attr("disabled", false);
},
success: function(data) {
$("button").attr("disabled", false);
}
});
return false;
});
});
</script>
</body>
</html>
""" % {'title':info.title, 'bstyle':bstyle, 'bstr':bstr})
def do_POST(self):
try:
self.server.page_info.callback(self.path)
self.send_response(200)
except ValueError:
self.send_response(400)
self.end_headers()
def StartHTTP(port, title, buttons, callback):
srv = BaseHTTPServer.HTTPServer(("0.0.0.0", port), RequestHandler)
srv.page_info = PageInfo(title, buttons, callback)
srv = thread.start_new_thread(srv.serve_forever, ())
return srv