home · contact · privacy
In HTTP module, wrap params parsing into ParamsParser.
authorChristian Heller <c.heller@plomlompom.de>
Wed, 27 Mar 2024 03:49:01 +0000 (04:49 +0100)
committerChristian Heller <c.heller@plomlompom.de>
Wed, 27 Mar 2024 03:49:01 +0000 (04:49 +0100)
plomtask/http.py

index 933662f51f1a9b78754371c2399969afa0ca75df..86db94d34ee5ea13630a3d550e9b9116cbfb1e48 100644 (file)
@@ -24,8 +24,31 @@ class TaskServer(HTTPServer):
         self.jinja = JinjaEnv(loader=JinjaFSLoader(TEMPLATES_DIR))
 
 
+class ParamsParser:  # pylint: disable=too-few-public-methods
+    """Wrapper for validating and retrieving GET params."""
+
+    def __init__(self, params: dict[str, list[str]]) -> None:
+        self.params = params
+
+    def get_str(self, key: str, default: str = '') -> str:
+        """Retrieve string value of key from self.params."""
+        if key not in self.params:
+            return default
+        return self.params[key][0]
+
+    def get_int_or_none(self, key: str) -> int | None:
+        """Retrieve int value of key yfrom self.params, on fail return None."""
+        if key not in self.params or not self.params[key]:
+            return None
+        val = self.params[key][0]
+        try:
+            return int(val)
+        except ValueError as e:
+            raise BadFormatException(f'Bad ?{key}= value: {val}') from e
+
+
 class PostvarsParser:
-    """Postvars wrapper for validating and retrieving posted form data."""
+    """Postvars wrapper for validating and retrieving form data."""
 
     def __init__(self, postvars: dict[str, list[str]]) -> None:
         self.postvars = postvars
@@ -54,22 +77,8 @@ class TaskHandler(BaseHTTPRequestHandler):
         """Handle any GET request."""
         try:
             conn, site, params = self._init_handling()
-            if 'calendar' == site:
-                start = params.get('start', [''])[0]
-                end = params.get('end', [''])[0]
-                html = self.do_GET_calendar(conn, start, end)
-            elif 'day' == site:
-                date = params.get('date', [todays_date()])[0]
-                html = self.do_GET_day(conn, date)
-            elif 'process' == site:
-                id_ = params.get('id', [None])[0]
-                try:
-                    id__ = int(id_) if id_ else None
-                except ValueError as e:
-                    raise BadFormatException(f'Bad ?id= value: {id_}') from e
-                html = self.do_GET_process(conn, id__)
-            elif 'processes' == site:
-                html = self.do_GET_processes(conn)
+            if site in {'calendar', 'day', 'process', 'processes'}:
+                html = getattr(self, f'do_GET_{site}')(conn, params)
             elif '' == site:
                 self._redirect('/day')
                 return
@@ -81,23 +90,30 @@ class TaskHandler(BaseHTTPRequestHandler):
             self._send_msg(error, code=error.http_code)
 
     def do_GET_calendar(self, conn: DatabaseConnection,
-                        start: str, end: str) -> str:
-        """Show Days."""
+                        params: ParamsParser) -> str:
+        """Show Days from ?start= to ?end=."""
+        start = params.get_str('start')
+        end = params.get_str('end')
         days = Day.all(conn, date_range=(start, end), fill_gaps=True)
         return self.server.jinja.get_template('calendar.html').render(
                 days=days, start=start, end=end)
 
-    def do_GET_day(self, conn: DatabaseConnection, date: str) -> str:
-        """Show single Day."""
+    def do_GET_day(self, conn: DatabaseConnection,
+                   params: ParamsParser) -> str:
+        """Show single Day of ?date=."""
+        date = params.get_str('date', todays_date())
         day = Day.by_date(conn, date, create=True)
         return self.server.jinja.get_template('day.html').render(day=day)
 
-    def do_GET_process(self, conn: DatabaseConnection, id_: int | None) -> str:
-        """Show process of id_."""
+    def do_GET_process(self, conn: DatabaseConnection,
+                       params: ParamsParser) -> str:
+        """Show process of ?id=."""
+        id_ = params.get_int_or_none('id')
         return self.server.jinja.get_template('process.html').render(
                 process=Process.by_id(conn, id_, create=True))
 
-    def do_GET_processes(self, conn: DatabaseConnection) -> str:
+    def do_GET_processes(self, conn: DatabaseConnection,
+                         _: ParamsParser) -> str:
         """Show all Processes."""
         return self.server.jinja.get_template('processes.html').render(
                 processes=Process.all(conn))
@@ -110,44 +126,37 @@ class TaskHandler(BaseHTTPRequestHandler):
             postvars = parse_qs(self.rfile.read(length).decode(),
                                 keep_blank_values=True)
             form_data = PostvarsParser(postvars)
-            if 'day' == site:
-                date = params.get('date', [''])[0]
-                self.do_POST_day(conn, date, form_data)
-            elif 'process' == site:
-                id_ = params.get('id', [''])[0]
-                try:
-                    id__ = int(id_) if id_ else None
-                except ValueError as e:
-                    raise BadFormatException(f'Bad ?id= value: {id_}') from e
-                self.do_POST_process(conn, id__, form_data)
+            if site in ('day', 'process'):
+                getattr(self, f'do_POST_{site}')(conn, params, form_data)
             conn.commit()
             conn.close()
             self._redirect('/')
         except HandledException as error:
             self._send_msg(error, code=error.http_code)
 
-    def do_POST_day(self, conn: DatabaseConnection, date: str,
+    def do_POST_day(self, conn: DatabaseConnection, params: ParamsParser,
                     form_data: PostvarsParser) -> None:
         """Update or insert Day of date and fields defined in postvars."""
+        date = params.get_str('date')
         day = Day.by_date(conn, date, create=True)
         day.comment = form_data.get_str('comment')
         day.save(conn)
 
-    def do_POST_process(self, conn: DatabaseConnection, id_: int | None,
+    def do_POST_process(self, conn: DatabaseConnection, params: ParamsParser,
                         form_data: PostvarsParser) -> None:
         """Update or insert Process of id_ and fields defined in postvars."""
+        id_ = params.get_int_or_none('id')
         process = Process.by_id(conn, id_, create=True)
         process.title.set(form_data.get_str('title'))
         process.description.set(form_data.get_str('description'))
         process.effort.set(form_data.get_float('effort'))
         process.save(conn)
 
-    def _init_handling(self) -> \
-            tuple[DatabaseConnection, str, dict[str, list[str]]]:
+    def _init_handling(self) -> tuple[DatabaseConnection, str, ParamsParser]:
         conn = DatabaseConnection(self.server.db)
         parsed_url = urlparse(self.path)
         site = path_split(parsed_url.path)[1]
-        params = parse_qs(parsed_url.query)
+        params = ParamsParser(parse_qs(parsed_url.query))
         return conn, site, params
 
     def _redirect(self, target: str) -> None: