2 """plom's task manager"""
3 from http.server import BaseHTTPRequestHandler
4 from http.server import HTTPServer
5 from urllib.parse import urlparse
6 from os.path import split as path_split
7 from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader
11 TEMPLATES_DIR = 'templates'
14 class HandledException(Exception):
15 """To identify Exceptions based on expected (if faulty) user behavior."""
18 class TaskServer(HTTPServer):
19 """Variant of HTTPServer that knows .jinja as Jinja Environment."""
21 def __init__(self, *args, **kwargs):
22 super().__init__(self, *args, **kwargs)
23 self.jinja = JinjaEnv(loader=JinjaFSLoader(TEMPLATES_DIR))
26 class TaskHandler(BaseHTTPRequestHandler):
27 """Handles single HTTP request."""
30 def send_html(self, html: str, code: int = 200):
31 """Send HTML as proper HTTP response."""
32 self.send_response(code)
34 self.wfile.write(bytes(html, 'utf-8'))
36 def send_msg(self, msg: str, code: int = 400):
37 """Send message in HTML formatting as HTTP response."""
38 html = self.server.jinja.get_template('msg.html').render(msg=msg)
39 self.send_html(html, code)
42 """Handle any GET request."""
44 parsed_url = urlparse(self.path)
45 site = path_split(parsed_url.path)[1]
46 if 'calendar' == site:
47 html = self.do_GET_calendar()
49 raise HandledException('Test!')
51 except HandledException as error:
54 def do_GET_calendar(self):
55 """Show sorted Days."""
56 days = [Day('2024-01-03'), Day('2024-01-01'), Day('2024-01-02')]
58 return self.server.jinja.get_template('calendar.html').render(
64 server = TaskServer(('localhost', HTTP_PORT), TaskHandler)
65 print(f'running at port {HTTP_PORT}')
67 server.serve_forever()
68 except KeyboardInterrupt:
69 print('aborting due to keyboard interrupt')
73 if __name__ == '__main__':
74 from sys import exit as sys_exit
77 except HandledException as e:
78 print(f'Aborting due to: {e}')