83 行
2.2 KiB
Python
83 行
2.2 KiB
Python
|
|
"""Side-effect-free coercion helpers shared by route handlers."""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
|
||
|
|
_TRUE_TEXT_VALUES = frozenset({"1", "true", "yes", "on"})
|
||
|
|
|
||
|
|
|
||
|
|
def optional_str(value: Any) -> str | None:
|
||
|
|
"""Return a stripped string, or ``None`` for missing/blank values."""
|
||
|
|
|
||
|
|
if value is None:
|
||
|
|
return None
|
||
|
|
text = str(value).strip()
|
||
|
|
return text or None
|
||
|
|
|
||
|
|
|
||
|
|
# Both names are used for this coercion across the backend. Keep the alias so
|
||
|
|
# route and service code can use the vocabulary that best fits the field.
|
||
|
|
optional_text = optional_str
|
||
|
|
|
||
|
|
|
||
|
|
def optional_int(value: Any) -> int | None:
|
||
|
|
"""Return an integer when coercion succeeds, otherwise ``None``."""
|
||
|
|
|
||
|
|
if value is None or value == "":
|
||
|
|
return None
|
||
|
|
try:
|
||
|
|
return int(value)
|
||
|
|
except (TypeError, ValueError):
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def optional_float(value: Any) -> float | None:
|
||
|
|
"""Return a float when coercion succeeds, otherwise ``None``."""
|
||
|
|
|
||
|
|
if value is None or value == "":
|
||
|
|
return None
|
||
|
|
try:
|
||
|
|
return float(value)
|
||
|
|
except (TypeError, ValueError):
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def int_or_default(value: Any, default: int) -> int:
|
||
|
|
"""Return an integer when coercion succeeds, otherwise ``default``.
|
||
|
|
|
||
|
|
Range normalization intentionally remains the responsibility of the
|
||
|
|
receiving service; route parsing only handles type coercion.
|
||
|
|
"""
|
||
|
|
|
||
|
|
try:
|
||
|
|
return int(value)
|
||
|
|
except (TypeError, ValueError):
|
||
|
|
return default
|
||
|
|
|
||
|
|
|
||
|
|
def as_bool(
|
||
|
|
value: Any,
|
||
|
|
*,
|
||
|
|
default: bool = False,
|
||
|
|
non_string_truthiness: bool = False,
|
||
|
|
) -> bool:
|
||
|
|
"""Coerce a route parameter to bool while preserving legacy semantics.
|
||
|
|
|
||
|
|
Strings accept the route-level true tokens ``1``, ``true``, ``yes`` and
|
||
|
|
``on``. Some existing routes historically applied Python truthiness to
|
||
|
|
non-string values; they opt into that behavior with
|
||
|
|
``non_string_truthiness=True``.
|
||
|
|
"""
|
||
|
|
|
||
|
|
if value is None:
|
||
|
|
return default
|
||
|
|
if isinstance(value, bool):
|
||
|
|
return value
|
||
|
|
if isinstance(value, str):
|
||
|
|
return value.strip().lower() in _TRUE_TEXT_VALUES
|
||
|
|
if non_string_truthiness:
|
||
|
|
return bool(value)
|
||
|
|
return str(value).strip().lower() in _TRUE_TEXT_VALUES
|