Ticket #12914: pyyaml.py-svn-modified

File pyyaml.py-svn-modified, 2.2 KB (added by Beuc, 15 years ago)

Use yaml faster C implementation when available

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