From: Christian Heller Date: Thu, 26 Dec 2024 09:27:36 +0000 (+0100) Subject: Simplify _ReqMap code. X-Git-Url: https://plomlompom.com/repos/%7B%7B%20web_path%20%7D%7D/static/%7B%7Bprefix%7D%7D/calendar?a=commitdiff_plain;h=refs%2Fheads%2Fmaster;p=ytplom Simplify _ReqMap code. --- diff --git a/src/ytplom/http.py b/src/ytplom/http.py index 0a6fa85..ad2cc85 100644 --- a/src/ytplom/http.py +++ b/src/ytplom/http.py @@ -5,7 +5,7 @@ from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler from json import dumps as json_dumps, loads as json_loads from pathlib import Path from time import sleep, time -from typing import Any, Generator, Optional +from typing import Any, Optional from urllib.parse import parse_qs, urlparse from urllib.request import urlretrieve from urllib.error import HTTPError @@ -79,15 +79,8 @@ class Server(ThreadingHTTPServer): class _ReqMap: """Wrapper over dictionary-like HTTP postings.""" - def __init__(self, map_as_str: str, is_json: bool = False) -> None: - self.is_json = is_json - self.as_str = map_as_str - - @property - def _as_dict(self) -> dict[str, list[str]]: - if self.is_json: - return json_loads(self.as_str) - return parse_qs(self.as_str) + def __init__(self, as_str: str, is_json: bool = False) -> None: + self._as_dict = json_loads(as_str) if is_json else parse_qs(as_str) def has_key(self, key: str) -> bool: """Return if key exists at all.""" @@ -101,11 +94,9 @@ class _ReqMap: """Return all values mapped to key.""" return self._as_dict.get(key, []) - def key_starting_with(self, start: str) -> Generator: - """From .as_dict yield key starting with start.""" - for k in self._as_dict: - if k.startswith(start): - yield k + def keys_starting_with(self, prefix: str) -> tuple[str, ...]: + """Return all keys present starting with prefix.""" + return tuple(k for k in self._as_dict if k.startswith(prefix)) class _TaskHandler(BaseHTTPRequestHandler): @@ -165,7 +156,7 @@ class _TaskHandler(BaseHTTPRequestHandler): self._redirect(Path(postvars.first_for('redir_target'))) def _receive_files_command(self, postvars: _ReqMap) -> None: - for k in postvars.key_starting_with('play_'): + for k in postvars.keys_starting_with('play_'): with DbConn() as conn: file = VideoFile.get_one( conn, Hash.from_b64(k.split('_', 1)[1]))