+class InputsParser:
+ """Wrapper for validating and retrieving dict-like HTTP inputs."""
+
+ def __init__(self, dict_: dict[str, list[str]],
+ strictness: bool = True) -> None:
+ self.inputs = dict_
+ self.strict = strictness
+
+ def get_str(self, key: str, default: str = '',
+ ignore_strict: bool = False) -> str:
+ """Retrieve single/first string value of key, or default."""
+ if key not in self.inputs.keys() or 0 == len(self.inputs[key]):
+ if self.strict and not ignore_strict:
+ raise BadFormatException(f'no value found for key {key}')
+ return default
+ return self.inputs[key][0]
+
+ def get_int(self, key: str) -> int:
+ """Retrieve single/first value of key as int, error if empty."""
+ val = self.get_int_or_none(key)
+ if val is None:
+ raise BadFormatException(f'unexpected empty value for: {key}')
+ return val
+
+ def get_int_or_none(self, key: str) -> int | None:
+ """Retrieve single/first value of key as int, return None if empty."""
+ val = self.get_str(key, ignore_strict=True)
+ if val == '':
+ return None
+ try:
+ return int(val)
+ except ValueError as e:
+ msg = f'cannot int form field value for key {key}: {val}'
+ raise BadFormatException(msg) from e
+
+ def get_float(self, key: str) -> float:
+ """Retrieve float value of key from self.postvars."""
+ val = self.get_str(key)
+ try:
+ return float(val)
+ except ValueError as e:
+ msg = f'cannot float form field value for key {key}: {val}'
+ raise BadFormatException(msg) from e
+
+ def get_all_str(self, key: str) -> list[str]:
+ """Retrieve list of string values at key."""
+ if key not in self.inputs.keys():
+ return []
+ return self.inputs[key]
+
+ def get_all_int(self, key: str) -> list[int]:
+ """Retrieve list of int values at key."""
+ all_str = self.get_all_str(key)
+ try:
+ return [int(s) for s in all_str if len(s) > 0]
+ except ValueError as e:
+ msg = f'cannot int a form field value for key {key} in: {all_str}'
+ raise BadFormatException(msg) from e
+
+