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