From: Christian Heller Date: Sat, 15 Jun 2024 06:39:46 +0000 (+0200) Subject: Minor HTTP module refactoring. X-Git-Url: https://plomlompom.com/repos/%7B%7Bdb.prefix%7D%7D/%7B%7B%20web_path%20%7D%7D/decks/process_descriptions?a=commitdiff_plain;h=a658d31f985ec9a08181005614c3d9876e046274;p=plomtask Minor HTTP module refactoring. --- diff --git a/plomtask/http.py b/plomtask/http.py index fc0059c..26c8b71 100644 --- a/plomtask/http.py +++ b/plomtask/http.py @@ -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')