Coverage for jutil/parse.py : 63%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from datetime import datetime
2from typing import Optional, Any
3from django.utils.translation import gettext as _
4from rest_framework.exceptions import ValidationError
5import pytz
6from dateutil.parser import parse as dateutil_parse
9TRUE_VALUES = (
10 'true',
11 '1',
12 'yes',
13)
15FALSE_VALUES = (
16 'none',
17 'null',
18 'false',
19 '0',
20 'no',
21)
24def parse_bool(v, default: Optional[bool] = None, exceptions: bool = True) -> Optional[bool]:
25 """
26 Parses boolean value
27 :param v: Input string
28 :param default: Default value if exceptions=False
29 :param exceptions: Raise exception on error or not
30 :return: bool
31 """
32 if isinstance(v, bool): 32 ↛ 33line 32 didn't jump to line 33, because the condition on line 32 was never true
33 return v
34 s = str(v).lower()
35 if s in TRUE_VALUES: 35 ↛ 36line 35 didn't jump to line 36, because the condition on line 35 was never true
36 return True
37 if s in FALSE_VALUES: 37 ↛ 38line 37 didn't jump to line 38, because the condition on line 37 was never true
38 return False
39 if exceptions: 39 ↛ 42line 39 didn't jump to line 42, because the condition on line 39 was never false
40 msg = _("%(value)s is not one of the available choices") % {'value': v}
41 raise ValidationError(msg)
42 return default
45def parse_datetime(v: str, default: Optional[datetime] = None, tz: Any = None, exceptions: bool = True) -> Optional[datetime]:
46 """
47 Parses str to timezone-aware datetime.
48 :param v: Input string to parse
49 :param default: Default value to return if exceptions=False
50 :param tz: Default pytz timezone or if None then use UTC as default
51 :param exceptions: Raise exception on error or not
52 :return: datetime
53 """
54 try:
55 t = dateutil_parse(v, default=datetime(2000, 1, 1))
56 if tz is None: 56 ↛ 58line 56 didn't jump to line 58, because the condition on line 56 was never false
57 tz = pytz.utc
58 return t if t.tzinfo else tz.localize(t)
59 except Exception:
60 if exceptions:
61 msg = _("“%(value)s” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.") % {'value': v}
62 raise ValidationError(msg)
63 return default