home · contact · privacy
Minor HTTP module refactoring.
authorChristian Heller <c.heller@plomlompom.de>
Sat, 15 Jun 2024 06:39:46 +0000 (08:39 +0200)
committerChristian Heller <c.heller@plomlompom.de>
Sat, 15 Jun 2024 06:39:46 +0000 (08:39 +0200)
plomtask/http.py

index fc0059c530e20c5e347a264703905b3fcadcb3df..26c8b719fec481e4106d66073a85844a1d16491a 100644 (file)
@@ -1,7 +1,7 @@
 """Web server stuff."""
 from __future__ import annotations
 from dataclasses import dataclass
-from typing import Any, Callable
+from typing import Any, Callable, Mapping
 from base64 import b64encode, b64decode
 from http.server import BaseHTTPRequestHandler
 from http.server import HTTPServer
@@ -106,8 +106,13 @@ class TaskHandler(BaseHTTPRequestHandler):
     _form_data: InputsParser
     _params: InputsParser
 
-    def _send_html(self, html: str, code: int = 200) -> None:
+    def _send_html(self,
+                   tmpl_name: str,
+                   ctx: Mapping[str, object],
+                   code: int = 200) -> None:
         """Send HTML as proper HTTP response."""
+        tmpl = self.server.jinja.get_template(tmpl_name)
+        html = tmpl.render(ctx)
         self.send_response(code)
         self.end_headers()
         self.wfile.write(bytes(html, 'utf-8'))
@@ -142,9 +147,8 @@ class TaskHandler(BaseHTTPRequestHandler):
                     for cls in (Day, Todo, Condition, Process, ProcessStep):
                         assert hasattr(cls, 'empty_cache')
                         cls.empty_cache()
-                    tmpl = self.server.jinja.get_template('msg.html')
-                    html = tmpl.render(msg=error)
-                    self._send_html(html, error.http_code)
+                    ctx = {'msg': error}
+                    self._send_html('msg.html', ctx, error.http_code)
                 finally:
                     self.conn.close()
             return wrapper
@@ -154,13 +158,11 @@ class TaskHandler(BaseHTTPRequestHandler):
     def do_GET(self, handler: Callable[[], str | dict[str, object]]
                ) -> str | None:
         """Render page with result of handler, or redirect if result is str."""
-        template = f'{self._site}.html'
+        tmpl_name = f'{self._site}.html'
         ctx_or_redir = handler()
-        if str == type(ctx_or_redir):
+        if isinstance(ctx_or_redir, str):
             return ctx_or_redir
-        assert isinstance(ctx_or_redir, dict)
-        html = self.server.jinja.get_template(template).render(**ctx_or_redir)
-        self._send_html(html)
+        self._send_html(tmpl_name, ctx_or_redir)
         return None
 
     @_request_wrapper('POST', 'Unknown POST target')