home · contact · privacy
Add script to unify all accounting servers into one.
[misc] / unite.py
1 from plomlib import PlomException, run_server, PlomHandler 
2 from urllib.parse import urlparse
3 from income_progress_bars import IncomeProgressHandler 
4 from calories import ConsumptionsHandler 
5 from ledger import LedgerHandler 
6 server_port = 8084
7
8
9 class UnitedRequestHandler(PlomHandler):
10     routes = {'GET':{}, 'POST':{}}
11     apps = {}
12
13     @classmethod
14     def register_app(cls, app):
15         name, data = app.app_init(app, cls)
16         cls.apps[name] = data
17
18     @classmethod
19     def add_route(cls, method, path, service):
20         if not method in cls.routes.keys():
21             cls.routes[method] = {}
22         cls.routes[method][path] = service 
23
24     def do_POST(self):
25         try: 
26             parsed_url = urlparse(self.path)
27             path_toks = parsed_url.path.split('/')
28             while len(path_toks) > 0:
29                 target_path = '/'.join(path_toks)
30                 if target_path in self.routes['POST'].keys(): 
31                     self.routes['POST'][target_path](self)
32                     return 
33                 path_toks.pop()
34             page = 'nothing to post?'
35             self.send_HTML(page)
36         except PlomException as e:
37             self.fail_400(e)
38
39     def do_GET(self):
40         try: 
41             parsed_url = urlparse(self.path)
42             path_toks = parsed_url.path.split('/')
43             while len(path_toks) > 0:
44                 target_path = '/'.join(path_toks)
45                 print(target_path)
46                 if target_path in self.routes['GET'].keys():                
47                     self.routes['GET'][target_path](self)
48                     return 
49                 path_toks.pop()
50             page = 'hi there!<br />'
51             for route in self.routes['GET']:
52                 page += f'<a href="{route}"/>{route}</a><br />'
53             self.send_HTML(page)
54         except PlomException as e:
55             self.fail_400(e)
56
57
58 if __name__ == "__main__":  
59     UnitedRequestHandler.register_app(IncomeProgressHandler)
60     UnitedRequestHandler.register_app(ConsumptionsHandler)
61     UnitedRequestHandler.register_app(LedgerHandler)
62     run_server(server_port, UnitedRequestHandler)