Coverage for /home/runner/work/viur-core/viur-core/viur/src/viur/core/utils/parse.py: 48%
21 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-27 07:59 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-27 07:59 +0000
1"""
2ViUR utility functions regarding parsing.
3"""
4import typing as t
5from viur.core import db
6import datetime
9def bool(value: t.Any, truthy_values: t.Iterable[str] = ("true", "yes", "1")) -> bool:
10 """
11 Parse a value into a boolean based on accepted truthy values.
13 This method takes a value, converts it to a lowercase string,
14 removes whitespace, and checks if it matches any of the provided
15 truthy values.
16 :param value: The value to be parsed into a boolean.
17 :param truthy_values: An iterable of strings representing truthy values.
18 Default is ("true", "yes", "1").
19 :returns: True if the value matches any of the truthy values, False otherwise.
20 """
21 return str(value).strip().lower() in truthy_values
24def sortorder(ident: str | int) -> db.SortOrder:
25 """
26 Parses a string defining a sort order into a db.SortOrder.
27 """
28 match str(ident or "").lower():
29 case "desc" | "descending" | "1":
30 return db.SortOrder.Descending
31 case "inverted_asc" | "inverted_ascending" | "2":
32 return db.SortOrder.InvertedAscending
33 case "inverted_desc" | "inverted_descending" | "3":
34 return db.SortOrder.InvertedDescending
35 case _: # everything else
36 return db.SortOrder.Ascending
39def timedelta(value: datetime.timedelta | int | float | str) -> datetime.timedelta:
40 """
41 Parse a value into a timedelta object.
43 This method takes a seconds value and converts it into
44 a timedelta object, if it is not already one.
45 :param value: The value to be parsed into a timedelta.
46 :returns: A timedelta object.
47 """
48 if isinstance(value, datetime.timedelta):
49 return value
50 if isinstance(value, str):
51 value = float(value)
52 return datetime.timedelta(seconds=value)