diff --git a/django/core/serializers/__init__.py b/django/core/serializers/__init__.py index f20258c416..494393f3cf 100644 --- a/django/core/serializers/__init__.py +++ b/django/core/serializers/__init__.py @@ -25,6 +25,13 @@ BUILTIN_SERIALIZERS = { "json" : "django.core.serializers.json", } +# Check for PyYaml and register the serializer if it's available. +try: + import yaml + BUILTIN_SERIALIZERS["yaml"] = "django.core.serializers.pyyaml" +except ImportError: + pass + _serializers = {} def register_serializer(format, serializer_module): diff --git a/django/core/serializers/pyyaml.py b/django/core/serializers/pyyaml.py new file mode 100644 index 0000000000..f45a511e79 --- /dev/null +++ b/django/core/serializers/pyyaml.py @@ -0,0 +1,36 @@ +""" +YAML serializer. + +Requires PyYaml (http://pyyaml.org/), but that's checked for in __init__. +""" + +import datetime +from django.core.serializers.python import Serializer as PythonSerializer +from django.core.serializers.python import Deserializer as PythonDeserializer +try: + from cStringIO import StringIO +except ImportError: + from StringIO import StringIO +import yaml + +class Serializer(PythonSerializer): + """ + Convert a queryset to JSON. + """ + def end_serialization(self): + yaml.dump(self.objects, self.stream, **self.options) + + def getvalue(self): + return self.stream.getvalue() + +def Deserializer(stream_or_string, **options): + """ + Deserialize a stream or string of JSON data. + """ + if isinstance(stream_or_string, basestring): + stream = StringIO(stream_or_string) + else: + stream = stream_or_string + for obj in PythonDeserializer(yaml.load(stream)): + yield obj +