server.py 2.05 KB
Newer Older
1
# Inspired by https://pythonbasics.org/webserver/
Anders B. Clausen's avatar
Anders B. Clausen committed
2
3
4
from http.server import BaseHTTPRequestHandler, HTTPServer
import time

5
hostName = '0.0.0.0'
Anders B. Clausen's avatar
Anders B. Clausen committed
6
7
serverPort = 1337

8
db = {
9
10
  'katrine-marie' : '[{"height":400,"blocks":[{"type":"Calendar","width":75},{"type":"ActiveCourses","width":25}]},{"height":250,"blocks":[{"type":"Deadlines","width":100}]},{"height":300,"blocks":[{"type":"Feed","width":50},{"type":"Mail","width":25},{"type":"Mail","width":25}]}]',
  'isaac' : '[{"height":400,"blocks":[{"type":"Calendar","width":75},{"type":"ActiveCourses","width":25}]},{"height":250,"blocks":[{"type":"Deadlines","width":100}]},{"height":300,"blocks":[{"type":"Feed","width":50},{"type":"Mail","width":25},{"type":"Mail","width":25}]}]'
11
12
}

Anders B. Clausen's avatar
Anders B. Clausen committed
13
class MyServer(BaseHTTPRequestHandler):
14
  def _set_ok_headers(self):
15
    self.send_response(200)
16
    self.send_header('Content-type', 'text/html')
17
    self.end_headers()
18
19
20
21
22
  
  def _set_err_headers(self):
    self.send_response(500)
    self.send_header('Content-type', 'text/html')
    self.end_headers()
23
    
24
  def handle_load_layout(self, id):
25
    if id in db:
26
      self._set_ok_headers()
27
      self.wfile.write(bytes(db[id], 'utf-8'))
28
    else:
29
      self._set_err_headers()
30
      self.wfile.write(bytes('Error: Could not find id ' + str(id), 'utf-8'))
31

32
33
  def handle_save_layout(self, id, data):
    db[id] = data.replace('%22', '"')
34

35
    self._set_ok_headers()
36
37

  def do_GET(self):
38
39
40
    # remove '/?' from path
    query = self.path[2:]
    fields = dict(f.split("=") for f in query.split("&"))
41

42
43
    if fields['type'] == "load":
      self.handle_load_layout(fields['id'])
44

45
46
    elif fields['type'] == "save":
      self.handle_save_layout(fields['id'], fields['data'])
Anders B. Clausen's avatar
Anders B. Clausen committed
47

48
49
50
51
    else:
      self._set_err_headers()
      self.wfile.write(bytes('Request type not supported', 'utf-8'))

52
if __name__ == '__main__':        
53
  webServer = HTTPServer((hostName, serverPort), MyServer)
54
  print('Server started http://%s:%s' % (hostName, serverPort))
Anders B. Clausen's avatar
Anders B. Clausen committed
55

56
57
58
59
  try:
    webServer.serve_forever()
  except KeyboardInterrupt:
    pass
Anders B. Clausen's avatar
Anders B. Clausen committed
60

61
  webServer.server_close()
62
  print('Server stopped.')