Ticket #8607: pyyaml.py

File pyyaml.py, 1.9 KB (added by antony_hatchkins <antony.hatchkins@…>, 16 years ago)

django\core\serializers\pyyaml.py

Line 
1"""
2YAML serializer.
3
4Requires PyYaml (http://pyyaml.org/), but that's checked for in __init__.
5"""
6
7from django.db import models
8from django.core.serializers.python import Serializer as PythonSerializer
9from django.core.serializers.python import Deserializer as PythonDeserializer
10try:
11 from cStringIO import StringIO
12except ImportError:
13 from StringIO import StringIO
14import yaml
15
16class Serializer(PythonSerializer):
17 """
18 Convert a queryset to YAML.
19 """
20
21 internal_use_only = False
22
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)
34
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)
39
40 def getvalue(self):
41 #return self.stream.getvalue()
42 if callable(getattr(self.stream, 'getvalue', None)):
43 return self.stream.getvalue()
44
45def Deserializer(stream_or_string, **options):
46 """
47 Deserialize a stream or string of YAML data.
48 """
49 if isinstance(stream_or_string, basestring):
50 stream = StringIO(stream_or_string)
51 else:
52 stream = stream_or_string
53 for obj in PythonDeserializer(yaml.load(stream)):
54 yield obj
55
Back to Top