Merged the queryset-refactor branch into trunk.
[fdr-django.git] / django / core / serializers / pyyaml.py
blob58cf59bed9e278b0b8a7025baaf71e5e82db0102
1 """
2 YAML serializer.
4 Requires PyYaml (http://pyyaml.org/), but that's checked for in __init__.
5 """
7 from django.db import models
8 from django.core.serializers.python import Serializer as PythonSerializer
9 from django.core.serializers.python import Deserializer as PythonDeserializer
10 try:
11 from cStringIO import StringIO
12 except ImportError:
13 from StringIO import StringIO
14 import yaml
16 class Serializer(PythonSerializer):
17 """
18 Convert a queryset to YAML.
19 """
21 internal_use_only = False
23 def handle_field(self, obj, field):
24 # A nasty special case: base YAML doesn't support serialization of time
25 # types (as opposed to dates or datetimes, which it does support). Since
26 # we want to use the "safe" serializer for better interoperability, we
27 # need to do something with those pesky times. Converting 'em to strings
28 # isn't perfect, but it's better than a "!!python/time" type which would
29 # halt deserialization under any other language.
30 if isinstance(field, models.TimeField) and getattr(obj, field.name) is not None:
31 self._current[field.name] = str(getattr(obj, field.name))
32 else:
33 super(Serializer, self).handle_field(obj, field)
35 def end_serialization(self):
36 self.options.pop('stream', None)
37 self.options.pop('fields', None)
38 yaml.safe_dump(self.objects, self.stream, **self.options)
40 def getvalue(self):
41 return self.stream.getvalue()
43 def Deserializer(stream_or_string, **options):
44 """
45 Deserialize a stream or string of YAML data.
46 """
47 if isinstance(stream_or_string, basestring):
48 stream = StringIO(stream_or_string)
49 else:
50 stream = stream_or_string
51 for obj in PythonDeserializer(yaml.load(stream)):
52 yield obj