| 1 |
""" |
| 2 |
YAML serializer. |
| 3 |
|
| 4 |
Requires PyYaml (https://pyyaml.org/), but that's checked for in __init__. |
| 5 |
""" |
| 6 |
|
| 7 |
import collections |
| 8 |
import datetime |
| 9 |
import decimal |
| 10 |
|
| 11 |
import yaml |
| 12 |
|
| 13 |
from django.core.serializers.base import DeserializationError |
| 14 |
from django.core.serializers.python import Deserializer as PythonDeserializer |
| 15 |
from django.core.serializers.python import Serializer as PythonSerializer |
| 16 |
|
| 17 |
# Use the C (faster) implementation if possible |
| 18 |
try: |
| 19 |
from yaml import CSafeDumper as SafeDumper |
| 20 |
from yaml import CSafeLoader as SafeLoader |
| 21 |
except ImportError: |
| 22 |
from yaml import SafeDumper, SafeLoader |
| 23 |
|
| 24 |
|
| 25 |
class DjangoSafeDumper(SafeDumper): |
| 26 |
def represent_decimal(self, data): |
| 27 |
return self.represent_scalar("tag:yaml.org,2002:str", str(data)) |
| 28 |
|
| 29 |
def represent_ordered_dict(self, data): |
| 30 |
return self.represent_mapping("tag:yaml.org,2002:map", data.items()) |
| 31 |
|
| 32 |
|
| 33 |
DjangoSafeDumper.add_representer(decimal.Decimal, DjangoSafeDumper.represent_decimal) |
| 34 |
DjangoSafeDumper.add_representer( |
| 35 |
collections.OrderedDict, DjangoSafeDumper.represent_ordered_dict |
| 36 |
) |
| 37 |
# Workaround to represent dictionaries in insertion order. |
| 38 |
# See https://github.com/yaml/pyyaml/pull/143. |
| 39 |
DjangoSafeDumper.add_representer(dict, DjangoSafeDumper.represent_ordered_dict) |
| 40 |
|
| 41 |
|
| 42 |
class Serializer(PythonSerializer): |
| 43 |
"""Convert a queryset to YAML.""" |
| 44 |
|
| 45 |
internal_use_only = False |
| 46 |
|
| 47 |
def _value_from_field(self, obj, field): |
| 48 |
# A nasty special case: base YAML doesn't support serialization of time |
| 49 |
# types (as opposed to dates or datetimes, which it does support). Since |
| 50 |
# we want to use the "safe" serializer for better interoperability, we |
| 51 |
# need to do something with those pesky times. Converting 'em to strings |
| 52 |
# isn't perfect, but it's better than a "!!python/time" type which would |
| 53 |
# halt deserialization under any other language. |
| 54 |
value = super()._value_from_field(obj, field) |
| 55 |
if isinstance(value, datetime.time): |
| 56 |
value = str(value) |
| 57 |
return value |
| 58 |
|
| 59 |
def end_serialization(self): |
| 60 |
self.options.setdefault("allow_unicode", True) |
| 61 |
yaml.dump(self.objects, self.stream, Dumper=DjangoSafeDumper, **self.options) |
| 62 |
|
| 63 |
def getvalue(self): |
| 64 |
# Grandparent super |
| 65 |
return super(PythonSerializer, self).getvalue() |
| 66 |
|
| 67 |
|
| 68 |
class Deserializer(PythonDeserializer): |
| 69 |
"""Deserialize a stream or string of YAML data.""" |
| 70 |
|
| 71 |
def __init__(self, stream_or_string, **options): |
| 72 |
stream = stream_or_string |
| 73 |
if isinstance(stream_or_string, bytes): |
| 74 |
stream = stream_or_string.decode() |
| 75 |
try: |
| 76 |
objects = yaml.load(stream, Loader=SafeLoader) |
| 77 |
except Exception as exc: |
| 78 |
raise DeserializationError() from exc |
| 79 |
super().__init__(objects, **options) |
| 80 |
|
| 81 |
def _handle_object(self, obj): |
| 82 |
try: |
| 83 |
yield from super()._handle_object(obj) |
| 84 |
except (GeneratorExit, DeserializationError): |
| 85 |
raise |
| 86 |
except Exception as exc: |
| 87 |
raise DeserializationError(f"Error deserializing object: {exc}") from exc |