Coverage for jutil/parse.py : 64%

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
1import logging
2from datetime import datetime
3from typing import Optional, Any
4from django.utils.translation import gettext as _
5from rest_framework.exceptions import ValidationError
6import pytz
7from dateutil.parser import parse as dateutil_parse
10logger = logging.getLogger(__name__)
13TRUE_VALUES = (
14 'true',
15 '1',
16 'yes',
17)
19FALSE_VALUES = (
20 'none',
21 'null',
22 'false',
23 '0',
24 'no',
25)
28def parse_bool(v, default: Optional[bool] = None, exceptions: bool = True) -> Optional[bool]:
29 """
30 Parses boolean value
31 :param v: Input string
32 :param default: Default value if exceptions=False
33 :param exceptions: Raise exception on error or not
34 :return: bool
35 """
36 if isinstance(v, bool): 36 ↛ 37line 36 didn't jump to line 37, because the condition on line 36 was never true
37 return v
38 s = str(v).lower()
39 if s in TRUE_VALUES: 39 ↛ 40line 39 didn't jump to line 40, because the condition on line 39 was never true
40 return True
41 if s in FALSE_VALUES: 41 ↛ 42line 41 didn't jump to line 42, because the condition on line 41 was never true
42 return False
43 if exceptions: 43 ↛ 46line 43 didn't jump to line 46, because the condition on line 43 was never false
44 msg = _("%(value)s is not one of the available choices") % {'value': v}
45 raise ValidationError(msg)
46 return default
49def parse_datetime(v: str, default: Optional[datetime] = None, tz: Any = None, exceptions: bool = True) -> Optional[datetime]:
50 """
51 Parses str to timezone-aware datetime.
52 :param v: Input string to parse
53 :param default: Default value to return if exceptions=False
54 :param tz: Default pytz timezone or if None then use UTC as default
55 :param exceptions: Raise exception on error or not
56 :return: datetime
57 """
58 try:
59 t = dateutil_parse(v, default=datetime(2000, 1, 1))
60 if tz is None: 60 ↛ 62line 60 didn't jump to line 62, because the condition on line 60 was never false
61 tz = pytz.utc
62 return t if t.tzinfo else tz.localize(t)
63 except Exception:
64 if exceptions:
65 msg = _("“%(value)s” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.") % {'value': v}
66 raise ValidationError(msg)
67 return default