2 from http.server import BaseHTTPRequestHandler
5 class PlomException(Exception):
11 def __init__(self, db_name):
12 self.db_file = db_name + ".json"
13 self.lock_file = db_name+ ".lock"
14 if os.path.exists(self.db_file):
15 with open(self.db_file, "r") as f:
19 if os.path.exists(self.lock_file):
20 raise PlomException('Sorry, lock file!')
21 f = open(self.lock_file, 'w+')
25 os.remove(self.lock_file)
29 from datetime import datetime, timedelta
30 # collect modification times of numbered .bak files
31 bak_prefix = f'{self.db_file}.bak.'
34 bak_as = f'{bak_prefix}{i}'
35 while os.path.exists(bak_as):
36 mod_time = os.path.getmtime(bak_as)
37 backup_dates += [str(datetime.fromtimestamp(mod_time))]
39 bak_as = f'{bak_prefix}{i}'
41 # collect what numbered .bak files to save: the older, the fewer; for each
42 # timedelta, keep the newest file that's older
43 ages_to_keep = [timedelta(minutes=4**i) for i in range(0, 8)]
46 for age in ages_to_keep:
48 for i, date in enumerate(reversed(backup_dates)):
49 if datetime.strptime(date, '%Y-%m-%d %H:%M:%S.%f') < limit:
50 unreversed_i = len(backup_dates) - i - 1
51 if unreversed_i not in to_save:
52 to_save += [unreversed_i]
55 # remove redundant backup files
59 source = f'{bak_prefix}{i}'
60 target = f'{bak_prefix}{j}'
61 shutil.move(source, target)
63 for i in range(j, len(backup_dates)):
65 os.remove(f'{bak_prefix}{i}')
66 except FileNotFoundError:
69 # put copy of current state at end of bak list
70 shutil.copy(self.db_file, f'{bak_prefix}{j}')
72 def write_text_to_db(self, text, mode='w'):
75 with open(self.db_file, mode) as f:
80 class PlomServer(BaseHTTPRequestHandler):
85 from http.server import HTTPServer
86 webServer = HTTPServer(('localhost', port), type(self))
87 print(f"Server started http://localhost:{port}")
89 webServer.serve_forever()
90 except KeyboardInterrupt:
92 webServer.server_close()
93 print("Server stopped.")
95 def fail_400(self, e):
96 page = f'{self.header}ERROR: {e}{self.footer}'
97 self.send_HTML(page, 400)
99 def send_HTML(self, html, code=200):
100 self.send_code_and_headers(code, [('Content-type', 'text/html')])
101 self.wfile.write(bytes(html, "utf-8"))
103 def send_code_and_headers(self, code, headers=[]):
104 self.send_response(code)
105 for fieldname, content in headers:
106 self.send_header(fieldname, content)
110 def run_server(port, server_class):
111 from http.server import HTTPServer
112 webServer = HTTPServer(('localhost', port), server_class)
113 print(f"Server started http://localhost:{port}")
115 webServer.serve_forever()
116 except KeyboardInterrupt:
118 webServer.server_close()
119 print("Server stopped.")