You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pyyaml.py 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """
  2. YAML serializer.
  3. Requires PyYaml (https://pyyaml.org/), but that's checked for in __init__.
  4. """
  5. import collections
  6. import decimal
  7. from io import StringIO
  8. import yaml
  9. from django.core.serializers.base import DeserializationError
  10. from django.core.serializers.python import (
  11. Deserializer as PythonDeserializer, Serializer as PythonSerializer,
  12. )
  13. from django.db import models
  14. # Use the C (faster) implementation if possible
  15. try:
  16. from yaml import CSafeLoader as SafeLoader
  17. from yaml import CSafeDumper as SafeDumper
  18. except ImportError:
  19. from yaml import SafeLoader, SafeDumper
  20. class DjangoSafeDumper(SafeDumper):
  21. def represent_decimal(self, data):
  22. return self.represent_scalar('tag:yaml.org,2002:str', str(data))
  23. def represent_ordered_dict(self, data):
  24. return self.represent_mapping('tag:yaml.org,2002:map', data.items())
  25. DjangoSafeDumper.add_representer(decimal.Decimal, DjangoSafeDumper.represent_decimal)
  26. DjangoSafeDumper.add_representer(collections.OrderedDict, DjangoSafeDumper.represent_ordered_dict)
  27. class Serializer(PythonSerializer):
  28. """Convert a queryset to YAML."""
  29. internal_use_only = False
  30. def handle_field(self, obj, field):
  31. # A nasty special case: base YAML doesn't support serialization of time
  32. # types (as opposed to dates or datetimes, which it does support). Since
  33. # we want to use the "safe" serializer for better interoperability, we
  34. # need to do something with those pesky times. Converting 'em to strings
  35. # isn't perfect, but it's better than a "!!python/time" type which would
  36. # halt deserialization under any other language.
  37. if isinstance(field, models.TimeField) and getattr(obj, field.name) is not None:
  38. self._current[field.name] = str(getattr(obj, field.name))
  39. else:
  40. super().handle_field(obj, field)
  41. def end_serialization(self):
  42. yaml.dump(self.objects, self.stream, Dumper=DjangoSafeDumper, **self.options)
  43. def getvalue(self):
  44. # Grandparent super
  45. return super(PythonSerializer, self).getvalue()
  46. def Deserializer(stream_or_string, **options):
  47. """Deserialize a stream or string of YAML data."""
  48. if isinstance(stream_or_string, bytes):
  49. stream_or_string = stream_or_string.decode()
  50. if isinstance(stream_or_string, str):
  51. stream = StringIO(stream_or_string)
  52. else:
  53. stream = stream_or_string
  54. try:
  55. yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options)
  56. except (GeneratorExit, DeserializationError):
  57. raise
  58. except Exception as exc:
  59. raise DeserializationError() from exc