diff --git a/api/obs/api/routes/exports.py b/api/obs/api/routes/exports.py index 26f4bd8..c71670b 100644 --- a/api/obs/api/routes/exports.py +++ b/api/obs/api/routes/exports.py @@ -12,8 +12,7 @@ from sanic.response import raw from sanic.exceptions import InvalidUsage from obs.api.app import app, json as json_response - -from .mapdetails import get_single_arg +from obs.api.utils import get_single_arg class ExportFormat(str, Enum): diff --git a/api/obs/api/routes/mapdetails.py b/api/obs/api/routes/mapdetails.py index 832ba02..9d08dd8 100644 --- a/api/obs/api/routes/mapdetails.py +++ b/api/obs/api/routes/mapdetails.py @@ -10,33 +10,11 @@ from sanic.exceptions import InvalidUsage from obs.api.app import api from obs.api.db import Road, OvertakingEvent, Track - - -from .stats import round_to +from obs.api.utils import round_to, get_single_arg round_distance = partial(round_to, multiples=0.001) round_speed = partial(round_to, multiples=0.1) -RAISE = object() - - -def get_single_arg(req, name, default=RAISE, convert=None): - try: - value = req.args[name][0] - except LookupError as e: - if default is RAISE: - raise InvalidUsage(f"missing `{name}`") from e - - value = default - - if convert is not None: - try: - value = convert(value) - except (ValueError, TypeError) as e: - raise InvalidUsage(f"invalid `{name}`") from e - - return value - def get_bearing(a, b): # longitude, latitude diff --git a/api/obs/api/routes/stats.py b/api/obs/api/routes/stats.py index 5292361..1e7b248 100644 --- a/api/obs/api/routes/stats.py +++ b/api/obs/api/routes/stats.py @@ -11,6 +11,7 @@ from sanicargs import parse_parameters from obs.api.app import api from obs.api.db import Track, OvertakingEvent, User +from obs.api.utils import round_to log = logging.getLogger(__name__) @@ -26,12 +27,6 @@ TRACK_DURATION_ROUNDING = 120 MINUMUM_RECORDING_DATE = datetime(2010, 1, 1) -def round_to(value: float, multiples: float) -> float: - if value is None: - return None - return round(value / multiples) * multiples - - @api.route("/stats") @parse_parameters async def stats(req, user: str = None, start: datetime = None, end: datetime = None): diff --git a/api/obs/api/utils.py b/api/obs/api/utils.py new file mode 100644 index 0000000..8175e9b --- /dev/null +++ b/api/obs/api/utils.py @@ -0,0 +1,27 @@ +from sanic.exceptions import InvalidUsage + +RAISE = object() + + +def get_single_arg(req, name, default=RAISE, convert=None): + try: + value = req.args[name][0] + except LookupError as e: + if default is RAISE: + raise InvalidUsage(f"missing `{name}`") from e + + value = default + + if convert is not None: + try: + value = convert(value) + except (ValueError, TypeError) as e: + raise InvalidUsage(f"invalid `{name}`: {str(e)}") from e + + return value + + +def round_to(value: float, multiples: float) -> float: + if value is None: + return None + return round(value / multiples) * multiples