-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple_server.py
80 lines (67 loc) · 2.38 KB
/
simple_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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import re
import time
import urllib
import os.path
import tornado.autoreload
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.template
from html_escape import *
from database import *
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("feedback.html")
def post(self):
msg = self.request.body
self.write("Information submitted!<br/>")
self.write("<a href='javascript:history.go(-1);'>Go back to last page</a><br/>")
self.write("<a href='/exit'>Shutdown the server</a><br/>")
he = HTMLEscape()
db = Database()
if msg != "":
for item in msg.split("&"):
tmp = item.split("=")
data = he.html_unescape(urllib.unquote_plus(tmp[0]))
# TODO: make html escape, regex clean, and other functions in util
data = re.sub("^[(0-9)|( :.\\-)]+", "", data).strip()
self.write(data + " is " + tmp[1] + ".<br/>")
db.input_data("general", int(tmp[1]), data)
# print db.output_data()
db.close()
class ExitHandler(tornado.web.RequestHandler):
def get(self):
self.write("Server shut down.")
server.stop()
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
pass
# print 'WebSocket Connection Opened...'
def on_message(self, message):
if os.path.isfile("fbtmp.html"):
with open("fbtmp.html", "r") as infile:
self.write_message(infile.read())
os.remove("fbtmp.html")
else:
self.write_message("")
# print 'WebSocket received:', message
time.sleep(0.1)
def on_close(self):
pass
# print 'WebSocket Connection Closed...'
class SimpleServer:
def __init__(self):
tornado.autoreload.start()
tornado.autoreload.watch("feedback.html")
self.application = tornado.web.Application([(r"/",MainHandler), (r'/ws', WSHandler), (r'/exit', ExitHandler)], autoreload=True)
def start(self, port=8888):
global server
self.application.listen(port)
server = tornado.ioloop.IOLoop.instance()
server.start()
def __del__(self):
server.stop()
# Test of this simpleserver. Server starts at port 8887.
if __name__ == "__main__":
ss = SimpleServer()
ss.start(8080)