Extract utility functions
This commit is contained in:
parent
412349cf4f
commit
8bb5d71186
|
@ -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):
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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):
|
||||
|
|
27
api/obs/api/utils.py
Normal file
27
api/obs/api/utils.py
Normal file
|
@ -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
|
Loading…
Reference in a new issue