| 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 |
from django.db import models |
|---|
| 11 |
from django.core.serializers.python import Serializer as PythonSerializer |
|---|
| 12 |
from django.core.serializers.python import Deserializer as PythonDeserializer |
|---|
| 13 |
|
|---|
| 14 |
class Serializer(PythonSerializer): |
|---|
| 15 |
""" |
|---|
| 16 |
Convert a queryset to YAML. |
|---|
| 17 |
""" |
|---|
| 18 |
|
|---|
| 19 |
internal_use_only = False |
|---|
| 20 |
|
|---|
| 21 |
def handle_field(self, obj, field): |
|---|
| 22 |
# A nasty special case: base YAML doesn't support serialization of time |
|---|
| 23 |
# types (as opposed to dates or datetimes, which it does support). Since |
|---|
| 24 |
# we want to use the "safe" serializer for better interoperability, we |
|---|
| 25 |
# need to do something with those pesky times. Converting 'em to strings |
|---|
| 26 |
# isn't perfect, but it's better than a "!!python/time" type which would |
|---|
| 27 |
# halt deserialization under any other language. |
|---|
| 28 |
if isinstance(field, models.TimeField) and getattr(obj, field.name) is not None: |
|---|
| 29 |
self._current[field.name] = str(getattr(obj, field.name)) |
|---|
| 30 |
else: |
|---|
| 31 |
super(Serializer, self).handle_field(obj, field) |
|---|
| 32 |
|
|---|
| 33 |
def end_serialization(self): |
|---|
| 34 |
self.options.pop('stream', None) |
|---|
| 35 |
self.options.pop('fields', None) |
|---|
| 36 |
yaml.safe_dump(self.objects, self.stream, **self.options) |
|---|
| 37 |
|
|---|
| 38 |
def getvalue(self): |
|---|
| 39 |
return self.stream.getvalue() |
|---|
| 40 |
|
|---|
| 41 |
def Deserializer(stream_or_string, **options): |
|---|
| 42 |
""" |
|---|
| 43 |
Deserialize a stream or string of YAML data. |
|---|
| 44 |
""" |
|---|
| 45 |
if isinstance(stream_or_string, basestring): |
|---|
| 46 |
stream = StringIO(stream_or_string) |
|---|
| 47 |
else: |
|---|
| 48 |
stream = stream_or_string |
|---|
| 49 |
for obj in PythonDeserializer(yaml.load(stream)): |
|---|
| 50 |
yield obj |
|---|