MCPcopy Index your code
hub / github.com/encode/django-rest-framework / default

Method default

rest_framework/utils/encoders.py:23–70  ·  view source on GitHub ↗
(self, obj)

Source from the content-addressed store, hash-verified

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
73class CustomScalar:

Calls 1

tolistMethod · 0.80