Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/core/serializers/json.py: 21%

77 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

1""" 

2Serialize data to/from JSON 

3""" 

4 

5import datetime 

6import decimal 

7import json 

8import uuid 

9 

10from django.core.serializers.base import DeserializationError 

11from django.core.serializers.python import Deserializer as PythonDeserializer 

12from django.core.serializers.python import Serializer as PythonSerializer 

13from django.utils.duration import duration_iso_string 

14from django.utils.functional import Promise 

15from django.utils.timezone import is_aware 

16 

17 

18class Serializer(PythonSerializer): 

19 """Convert a queryset to JSON.""" 

20 

21 internal_use_only = False 

22 

23 def _init_options(self): 

24 self._current = None 

25 self.json_kwargs = self.options.copy() 

26 self.json_kwargs.pop("stream", None) 

27 self.json_kwargs.pop("fields", None) 

28 if self.options.get("indent"): 

29 # Prevent trailing spaces 

30 self.json_kwargs["separators"] = (",", ": ") 

31 self.json_kwargs.setdefault("cls", DjangoJSONEncoder) 

32 self.json_kwargs.setdefault("ensure_ascii", False) 

33 

34 def start_serialization(self): 

35 self._init_options() 

36 self.stream.write("[") 

37 

38 def end_serialization(self): 

39 if self.options.get("indent"): 

40 self.stream.write("\n") 

41 self.stream.write("]") 

42 if self.options.get("indent"): 

43 self.stream.write("\n") 

44 

45 def end_object(self, obj): 

46 # self._current has the field data 

47 indent = self.options.get("indent") 

48 if not self.first: 

49 self.stream.write(",") 

50 if not indent: 

51 self.stream.write(" ") 

52 if indent: 

53 self.stream.write("\n") 

54 json.dump(self.get_dump_object(obj), self.stream, **self.json_kwargs) 

55 self._current = None 

56 

57 def getvalue(self): 

58 # Grandparent super 

59 return super(PythonSerializer, self).getvalue() 

60 

61 

62def Deserializer(stream_or_string, **options): 

63 """Deserialize a stream or string of JSON data.""" 

64 if not isinstance(stream_or_string, (bytes, str)): 

65 stream_or_string = stream_or_string.read() 

66 if isinstance(stream_or_string, bytes): 

67 stream_or_string = stream_or_string.decode() 

68 try: 

69 objects = json.loads(stream_or_string) 

70 yield from PythonDeserializer(objects, **options) 

71 except (GeneratorExit, DeserializationError): 

72 raise 

73 except Exception as exc: 

74 raise DeserializationError() from exc 

75 

76 

77class DjangoJSONEncoder(json.JSONEncoder): 

78 """ 

79 JSONEncoder subclass that knows how to encode date/time, decimal types, and 

80 UUIDs. 

81 """ 

82 

83 def default(self, o): 

84 # See "Date Time String Format" in the ECMA-262 specification. 

85 if isinstance(o, datetime.datetime): 

86 r = o.isoformat() 

87 if o.microsecond: 

88 r = r[:23] + r[26:] 

89 if r.endswith("+00:00"): 

90 r = r[:-6] + "Z" 

91 return r 

92 elif isinstance(o, datetime.date): 

93 return o.isoformat() 

94 elif isinstance(o, datetime.time): 

95 if is_aware(o): 

96 raise ValueError("JSON can't represent timezone-aware times.") 

97 r = o.isoformat() 

98 if o.microsecond: 

99 r = r[:12] 

100 return r 

101 elif isinstance(o, datetime.timedelta): 

102 return duration_iso_string(o) 

103 elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)): 

104 return str(o) 

105 else: 

106 return super().default(o)