-
Notifications
You must be signed in to change notification settings - Fork 1
/
serve
executable file
·75 lines (67 loc) · 2.31 KB
/
serve
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
#!/usr/bin/env python
import ws
import http.server
import socketserver
import json
class CoiotServer(http.server.SimpleHTTPRequestHandler):
def __init__(self, request, client_address, server):
self.ws = ws.CoiotWs()
super(CoiotServer, self).__init__(request, client_address, server)
def ws_get(self):
response = json.dumps(self.ws.get(self.path)).encode('utf-8')
if response == None:
self.send_response(204)
self.end_headers()
else:
self.send_response(200)
self.send_header("Content-type", "application/json")
self.send_header("Content-length", len(response))
self.end_headers()
self.wfile.write(response)
def ws_set(self):
r = self.rfile.read(int(self.headers.get("Content-Length"))).decode('utf-8')
if r:
self.ws.set(self.path, json.loads(r))
self.send_response(204)
else:
self.send_error(400, "PUT requires a value")
self.end_headers()
def do_GET(self):
self.path = self.path.replace("../", "")
if self.path.replace("/", "") == "":
self.path = "/html/index.html"
elif self.path == "/favicon.ico":
self.path = "/img/" + self.path
elif self.path.startswith("/img/"):
pass
elif self.path.startswith("/ws/"):
try:
self.ws_get()
except ws.CoiotWsError as e:
self.send_error(e.code, e.message)
if e.code >= 500:
raise
except Exception as e:
self.send_error(500, str(e))
raise
return
else:
self.send_error(404)
return
super(CoiotServer, self).do_GET()
def do_PUT(self):
if self.path.startswith("/ws/"):
try:
self.ws_set()
except ws.CoiotWsError as e:
self.send_error(e.code, e.message)
if e.code >= 500:
raise
except Exception as e:
self.send_error(500, str(e))
raise
return
super(CoiotServer, self).do_PUT()
if __name__ == "__main__":
with http.server.HTTPServer(("", 8000), CoiotServer) as s:
s.serve_forever()