1 from http.server import BaseHTTPRequestHandler, HTTPServer
7 def build_page(entries):
16 <form action="/" method="POST">
18 <input name="energy" type="number" step="1" min="-2" max="2" value="0" />
20 <input name="comment" type="text" />
21 <input type="submit" value="submit!" />
28 <tr><th>datetime</th><th>energy level</th><th>comment</th></tr>
40 db_name = "energy_tracker"
41 self.db_file = db_name + ".json"
42 self.lock_file = db_name+ ".lock"
44 if os.path.exists(self.db_file):
45 with open(self.db_file, "r") as f:
46 self.from_dict(json.load(f))
48 def from_dict(self, d):
56 if os.path.exists(self.lock_file):
57 raise LockFileDetected
58 if os.path.exists(self.db_file):
59 shutil.copy(self.db_file, self.db_file + ".bak")
60 f = open(self.lock_file, "w+")
62 with open(self.db_file, "w") as f:
63 json.dump(self.to_dict(), f)
64 os.remove(self.lock_file)
68 class MyServer(BaseHTTPRequestHandler):
72 from urllib.parse import parse_qs
73 length = int(self.headers['content-length'])
74 postvars = parse_qs(self.rfile.read(length), keep_blank_values=1)
76 db.entries[str(datetime.datetime.now())[:19]] = [int(postvars[b'energy'][0].decode()), postvars[b'comment'][0].decode()]
79 self.send_response(302)
80 self.send_header('Location', '/')
82 except LockFileDetected:
83 self.send_response(400)
85 self.wfile.write(bytes("Sorry, lock file!", "utf-8"))
88 self.send_response(200)
89 self.send_header("Content-type", "text/html")
93 for datetime, data in db.entries.items():
94 entries = "<tr><td>%s</td><td class=\"energy_cell\">%s</td><td>%s</td></tr>\n" % (datetime, data[0], data[1]) + entries
95 page = build_page(entries)
96 self.wfile.write(bytes(page, "utf-8"))
100 hostName = "localhost"
102 if __name__ == "__main__":
103 webServer = HTTPServer((hostName, serverPort), MyServer)
104 print("Server started http://%s:%s" % (hostName, serverPort))
106 webServer.serve_forever()
107 except KeyboardInterrupt:
109 webServer.server_close()
110 print("Server stopped.")