home · contact · privacy
739b00f774430cb62d41eb574168eda64cb8c948
[misc] / plomlib.py
1 import os
2 from http.server import BaseHTTPRequestHandler 
3
4
5 class PlomException(Exception):
6     pass
7
8
9 class PlomDB:
10
11     def __init__(self, db_name):
12         self.db_file = db_name
13         self.lock_file = db_name+ '.lock'
14         if os.path.exists(self.db_file):
15             with open(self.db_file, 'r') as f:
16                 self.read_db_file(f)
17
18     def lock(self):
19         if os.path.exists(self.lock_file):
20             raise PlomException('Sorry, lock file!')
21         f = open(self.lock_file, 'w+')
22         f.close()
23
24     def unlock(self):
25         os.remove(self.lock_file)
26
27     def backup(self):
28         import shutil
29         from datetime import datetime, timedelta
30         if not os.path.exists(self.db_file):
31             return
32
33         # collect modification times of numbered .bak files
34         bak_prefix = f'{self.db_file}.bak.'
35         backup_dates = []
36         i = 0
37         bak_as = f'{bak_prefix}{i}'
38         while os.path.exists(bak_as):
39             mod_time = os.path.getmtime(bak_as)
40             backup_dates += [str(datetime.fromtimestamp(mod_time))]
41             i += 1
42             bak_as = f'{bak_prefix}{i}'
43
44         # collect what numbered .bak files to save: the older, the fewer; for each
45         # timedelta, keep the newest file that's older
46         ages_to_keep = [timedelta(minutes=4**i) for i in range(0, 8)]
47         now = datetime.now() 
48         to_save = []
49         for age in ages_to_keep:
50             limit = now - age 
51             for i, date in enumerate(reversed(backup_dates)):
52                 if datetime.strptime(date, '%Y-%m-%d %H:%M:%S.%f') < limit:
53                     unreversed_i = len(backup_dates) - i - 1
54                     if unreversed_i not in to_save:
55                         to_save += [unreversed_i]
56                     break
57
58         # remove redundant backup files 
59         j = 0
60         for i in to_save:
61             if i != j:
62                 source = f'{bak_prefix}{i}'
63                 target = f'{bak_prefix}{j}'
64                 shutil.move(source, target)
65             j += 1
66         for i in range(j, len(backup_dates)):
67             try:
68                 os.remove(f'{bak_prefix}{i}')
69             except FileNotFoundError:
70                 pass
71
72         # put copy of current state at end of bak list 
73         shutil.copy(self.db_file, f'{bak_prefix}{j}')
74
75     def write_text_to_db(self, text, mode='w'):
76         self.lock()
77         self.backup()
78         with open(self.db_file, mode) as f:
79             f.write(text);
80         self.unlock()
81
82
83 class PlomHandler(BaseHTTPRequestHandler): 
84     homepage = '/'
85     html_head = '<!DOCTYPE html>\n<html>\n<meta charset="UTF-8">'
86     html_foot = '</body>\n</html>'
87     
88     def fail_400(self, e):
89         self.send_HTML(f'ERROR: {e}', 400)
90
91     def send_HTML(self, html, code=200):
92         self.send_code_and_headers(code, [('Content-type', 'text/html')])
93         self.wfile.write(bytes(f'{self.html_head}\n{html}\n{self.html_foot}', 'utf-8'))
94
95     def send_code_and_headers(self, code, headers=[]):
96         self.send_response(code)
97         for fieldname, content in headers:
98             self.send_header(fieldname, content)
99         self.end_headers()
100
101     def redirect(self, url='/'):
102         self.send_code_and_headers(302, [('Location', url)])
103
104     def try_do(self, do_method):
105         try:
106             do_method() 
107         except PlomException as e:
108             self.fail_400(e)
109
110
111
112 def run_server(port, handler_class):
113     from http.server import HTTPServer
114     webServer = HTTPServer(('localhost', port), handler_class)
115     print(f"Server started http://localhost:{port}")
116     try:
117         webServer.serve_forever()
118     except KeyboardInterrupt:
119         pass
120     webServer.server_close()
121     print("Server stopped.")