From: Christian Heller Date: Mon, 24 Jul 2023 23:57:07 +0000 (+0200) Subject: Add energy tracker script. X-Git-Url: https://plomlompom.com/repos/%7B%7Bdb.prefix%7D%7D/%7B%7B%20web_path%20%7D%7D/static/index.html?a=commitdiff_plain;h=ed1cc7a1f866f5cc8bb039e93747118c7fcb9fce;p=misc Add energy tracker script. --- diff --git a/energy_tracker.py b/energy_tracker.py new file mode 100644 index 0000000..204b582 --- /dev/null +++ b/energy_tracker.py @@ -0,0 +1,110 @@ +from http.server import BaseHTTPRequestHandler, HTTPServer +import os +import json + + + +def build_page(entries): + return """ + + + +
+energy level: + +comment: + + +
""" + f""" +
+ +[tracking] + + + +{entries} +
datetimeenergy levelcomment
""" + """ +
+ +""" + + + +class Database: + + def __init__(self): + db_name = "energy_tracker" + self.db_file = db_name + ".json" + self.lock_file = db_name+ ".lock" + self.entries = {} + if os.path.exists(self.db_file): + with open(self.db_file, "r") as f: + self.from_dict(json.load(f)) + + def from_dict(self, d): + self.entries = d + + def to_dict(self): + return self.entries + + def write(self): + import shutil + if os.path.exists(self.lock_file): + raise LockFileDetected + if os.path.exists(self.db_file): + shutil.copy(self.db_file, self.db_file + ".bak") + f = open(self.lock_file, "w+") + f.close() + with open(self.db_file, "w") as f: + json.dump(self.to_dict(), f) + os.remove(self.lock_file) + + + +class MyServer(BaseHTTPRequestHandler): + + def do_POST(self): + import datetime + from urllib.parse import parse_qs + length = int(self.headers['content-length']) + postvars = parse_qs(self.rfile.read(length), keep_blank_values=1) + db = Database() + db.entries[str(datetime.datetime.now())[:19]] = [int(postvars[b'energy'][0].decode()), postvars[b'comment'][0].decode()] + try: + db.write() + self.send_response(302) + self.send_header('Location', '/') + self.end_headers() + except LockFileDetected: + self.send_response(400) + self.end_headers() + self.wfile.write(bytes("Sorry, lock file!", "utf-8")) + + def do_GET(self): + self.send_response(200) + self.send_header("Content-type", "text/html") + self.end_headers() + db = Database() + entries = "" + for datetime, data in db.entries.items(): + entries = "%s%s%s\n" % (datetime, data[0], data[1]) + entries + page = build_page(entries) + self.wfile.write(bytes(page, "utf-8")) + + + +hostName = "localhost" +serverPort = 8080 +if __name__ == "__main__": + webServer = HTTPServer((hostName, serverPort), MyServer) + print("Server started http://%s:%s" % (hostName, serverPort)) + try: + webServer.serve_forever() + except KeyboardInterrupt: + pass + webServer.server_close() + print("Server stopped.")