| 1 |
""" |
| 2 |
Helper classes for parsers. |
| 3 |
""" |
| 4 |
|
| 5 |
import contextlib |
| 6 |
import datetime |
| 7 |
import decimal |
| 8 |
import ipaddress |
| 9 |
import json # noqa |
| 10 |
import uuid |
| 11 |
|
| 12 |
from django.db.models.query import QuerySet |
| 13 |
from django.utils import timezone |
| 14 |
from django.utils.encoding import force_str |
| 15 |
from django.utils.functional import Promise |
| 16 |
|
| 17 |
|
| 18 |
class JSONEncoder(json.JSONEncoder): |
| 19 |
""" |
| 20 |
JSONEncoder subclass that knows how to encode date/time/timedelta, |
| 21 |
decimal types, generators and other basic python objects. |
| 22 |
""" |
| 23 |
def default(self, obj): |
| 24 |
# For Date Time string spec, see ECMA 262 |
| 25 |
# https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 |
| 26 |
if isinstance(obj, Promise): |
| 27 |
return force_str(obj) |
| 28 |
elif isinstance(obj, datetime.datetime): |
| 29 |
representation = obj.isoformat() |
| 30 |
if representation.endswith('+00:00'): |
| 31 |
representation = representation[:-6] + 'Z' |
| 32 |
return representation |
| 33 |
elif isinstance(obj, datetime.date): |
| 34 |
return obj.isoformat() |
| 35 |
elif isinstance(obj, datetime.time): |
| 36 |
if timezone and timezone.is_aware(obj): |
| 37 |
raise ValueError("JSON can't represent timezone-aware times.") |
| 38 |
representation = obj.isoformat() |
| 39 |
return representation |
| 40 |
elif isinstance(obj, datetime.timedelta): |
| 41 |
return str(obj.total_seconds()) |
| 42 |
elif isinstance(obj, decimal.Decimal): |
| 43 |
# Serializers will coerce decimals to strings by default. |
| 44 |
return float(obj) |
| 45 |
elif isinstance(obj, uuid.UUID): |
| 46 |
return str(obj) |
| 47 |
elif isinstance(obj, ( |
| 48 |
ipaddress.IPv4Address, |
| 49 |
ipaddress.IPv6Address, |
| 50 |
ipaddress.IPv4Network, |
| 51 |
ipaddress.IPv6Network, |
| 52 |
ipaddress.IPv4Interface, |
| 53 |
ipaddress.IPv6Interface) |
| 54 |
): |
| 55 |
return str(obj) |
| 56 |
elif isinstance(obj, QuerySet): |
| 57 |
return tuple(obj) |
| 58 |
elif isinstance(obj, bytes): |
| 59 |
# Best-effort for binary blobs. See #4187. |
| 60 |
return obj.decode() |
| 61 |
elif hasattr(obj, 'tolist'): |
| 62 |
# Numpy arrays and array scalars. |
| 63 |
return obj.tolist() |
| 64 |
elif hasattr(obj, '__getitem__'): |
| 65 |
cls = (list if isinstance(obj, (list, tuple)) else dict) |
| 66 |
with contextlib.suppress(Exception): |
| 67 |
return cls(obj) |
| 68 |
elif hasattr(obj, '__iter__'): |
| 69 |
return tuple(item for item in obj) |
| 70 |
return super().default(obj) |
| 71 |
|
| 72 |
|
| 73 |
class CustomScalar: |
| 74 |
""" |
| 75 |
CustomScalar that knows how to encode timedelta that renderer |
| 76 |
can understand. |
| 77 |
""" |
| 78 |
@classmethod |
| 79 |
def represent_timedelta(cls, dumper, data): |
| 80 |
value = str(data.total_seconds()) |
| 81 |
return dumper.represent_scalar('tag:yaml.org,2002:str', value) |