-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.py
56 lines (42 loc) · 1.55 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
56
"""
Creates an HTTP server with basic websocket communication.
"""
import argparse
import json
import os
import traceback
import webbrowser
import tornado.web
import tornado.websocket
import methods
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html", port=args.port)
class WebSocket(tornado.websocket.WebSocketHandler):
def on_message(self, message):
"""Evaluates the function pointed to by json-rpc."""
json_rpc = json.loads(message)
try:
result = getattr(methods,
json_rpc["method"])(**json_rpc["params"])
error = None
except:
result = traceback.format_exc()
error = 1
self.write_message(json.dumps({"result": result, "error": error,
"id": json_rpc["id"]},
separators=(",", ":")))
parser = argparse.ArgumentParser(description="Starts a webserver for stuff.")
parser.add_argument("--port", type=int, default=8000, help="The port on which "
"to serve the website.")
args = parser.parse_args()
handlers = [(r"/", IndexHandler), (r"/websocket", WebSocket),
(r'/static/(.*)', tornado.web.StaticFileHandler,
{'path': os.path.normpath(os.path.dirname(__file__))})]
application = tornado.web.Application(handlers)
application.listen(args.port)
webbrowser.open("http://localhost:%d/" % args.port, new=2)
try:
tornado.ioloop.IOLoop.instance().start()
except:
methods.gpio.cleanup()