Révision ddb02348
Ajouté par Benjamin Dauvergne il y a environ 10 ans
entrouvert/djommon/serializers/json.py | ||
---|---|---|
1 |
import json |
|
2 |
|
|
3 |
from django.utils import six |
|
4 |
from django.core.serializers.json import Serializer as JSONSerializer |
|
5 |
from django.core.serializers.python import Deserializer as \ |
|
6 |
PythonDeserializer, _get_model |
|
7 |
from django.core.serializers.base import DeserializationError |
|
8 |
|
|
9 |
class Serializer(JSONSerializer): |
|
10 |
def get_dump_object(self, obj): |
|
11 |
d = super(Serializer, self).get_dump_object(obj) |
|
12 |
if self.use_natural_keys and hasattr(obj, 'natural_key'): |
|
13 |
d['pk'] = obj.natural_key() |
|
14 |
return d |
|
15 |
|
|
16 |
def Deserializer(stream_or_string, **options): |
|
17 |
""" |
|
18 |
Deserialize a stream or string of JSON data. |
|
19 |
""" |
|
20 |
if not isinstance(stream_or_string, (bytes, six.string_types)): |
|
21 |
stream_or_string = stream_or_string.read() |
|
22 |
if isinstance(stream_or_string, bytes): |
|
23 |
stream_or_string = stream_or_string.decode('utf-8') |
|
24 |
try: |
|
25 |
objects = json.loads(stream_or_string) |
|
26 |
for obj in objects: |
|
27 |
Model = _get_model(obj['model']) |
|
28 |
if isinstance(obj['pk'], (tuple, list)): |
|
29 |
o = Model.objects.get_by_natural_key(*obj['pk']) |
|
30 |
obj['pk'] = o.pk |
|
31 |
for obj in PythonDeserializer(objects, **options): |
|
32 |
yield obj |
|
33 |
except GeneratorExit: |
|
34 |
raise |
|
35 |
except Exception as e: |
|
36 |
# Map to deserializer error |
|
37 |
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2]) |
Formats disponibles : Unified diff
djommon: add JSON serializer supporting natural primary keys