Skip to content

Commit 9d001fa

Browse files
committed
unicode: Made the serializers unicode-aware. Refs #3878, #4227.
git-svn-id: http://code.djangoproject.com/svn/django/branches/unicode@5248 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent 0e4c383 commit 9d001fa

File tree

6 files changed

+103
-102
lines changed

6 files changed

+103
-102
lines changed

django/core/serializers/__init__.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
>>> from django.core import serializers
77
>>> json = serializers.serialize("json", some_query_set)
88
>>> objects = list(serializers.deserialize("json", json))
9-
9+
1010
To add your own serializers, use the SERIALIZATION_MODULES setting::
1111
1212
SERIALIZATION_MODULES = {
@@ -30,19 +30,19 @@
3030
import yaml
3131
BUILTIN_SERIALIZERS["yaml"] = "django.core.serializers.pyyaml"
3232
except ImportError:
33-
pass
33+
pass
3434

3535
_serializers = {}
36-
36+
3737
def register_serializer(format, serializer_module):
3838
"""Register a new serializer by passing in a module name."""
3939
module = __import__(serializer_module, {}, {}, [''])
4040
_serializers[format] = module
41-
41+
4242
def unregister_serializer(format):
4343
"""Unregister a given serializer"""
4444
del _serializers[format]
45-
45+
4646
def get_serializer(format):
4747
if not _serializers:
4848
_load_serializers()
@@ -52,12 +52,12 @@ def get_serializer_formats():
5252
if not _serializers:
5353
_load_serializers()
5454
return _serializers.keys()
55-
55+
5656
def get_deserializer(format):
5757
if not _serializers:
5858
_load_serializers()
5959
return _serializers[format].Deserializer
60-
60+
6161
def serialize(format, queryset, **options):
6262
"""
6363
Serialize a queryset (or any iterator that returns database objects) using
@@ -87,4 +87,4 @@ def _load_serializers():
8787
register_serializer(format, BUILTIN_SERIALIZERS[format])
8888
if hasattr(settings, "SERIALIZATION_MODULES"):
8989
for format in settings.SERIALIZATION_MODULES:
90-
register_serializer(format, settings.SERIALIZATION_MODULES[format])
90+
register_serializer(format, settings.SERIALIZATION_MODULES[format])

django/core/serializers/base.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
except ImportError:
88
from StringIO import StringIO
99
from django.db import models
10+
from django.utils.encoding import smart_str, smart_unicode
1011

1112
class SerializationError(Exception):
1213
"""Something bad happened during serialization."""
@@ -59,7 +60,7 @@ def get_string_value(self, obj, field):
5960
value = getattr(obj, "get_%s_url" % field.name, lambda: None)()
6061
else:
6162
value = field.flatten_data(follow=None, obj=obj).get(field.name, "")
62-
return str(value)
63+
return smart_unicode(value)
6364

6465
def start_serialization(self):
6566
"""
@@ -154,7 +155,7 @@ def __init__(self, obj, m2m_data=None):
154155
self.m2m_data = m2m_data
155156

156157
def __repr__(self):
157-
return "<DeserializedObject: %s>" % str(self.object)
158+
return "<DeserializedObject: %s>" % smart_str(self.object)
158159

159160
def save(self, save_m2m=True):
160161
self.object.save()

django/core/serializers/python.py

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -7,49 +7,50 @@
77
from django.conf import settings
88
from django.core.serializers import base
99
from django.db import models
10+
from django.utils.encoding import smart_unicode
1011

1112
class Serializer(base.Serializer):
1213
"""
1314
Serializes a QuerySet to basic Python objects.
1415
"""
15-
16+
1617
def start_serialization(self):
1718
self._current = None
1819
self.objects = []
19-
20+
2021
def end_serialization(self):
2122
pass
22-
23+
2324
def start_object(self, obj):
2425
self._current = {}
25-
26+
2627
def end_object(self, obj):
2728
self.objects.append({
28-
"model" : str(obj._meta),
29-
"pk" : str(obj._get_pk_val()),
29+
"model" : smart_unicode(obj._meta),
30+
"pk" : smart_unicode(obj._get_pk_val()),
3031
"fields" : self._current
3132
})
3233
self._current = None
33-
34+
3435
def handle_field(self, obj, field):
3536
self._current[field.name] = getattr(obj, field.name)
36-
37+
3738
def handle_fk_field(self, obj, field):
3839
related = getattr(obj, field.name)
3940
if related is not None:
4041
related = getattr(related, field.rel.field_name)
4142
self._current[field.name] = related
42-
43+
4344
def handle_m2m_field(self, obj, field):
4445
self._current[field.name] = [related._get_pk_val() for related in getattr(obj, field.name).iterator()]
45-
46+
4647
def getvalue(self):
4748
return self.objects
4849

4950
def Deserializer(object_list, **options):
5051
"""
5152
Deserialize simple Python objects back into Django ORM instances.
52-
53+
5354
It's expected that you pass the Python objects themselves (instead of a
5455
stream or a string) to the constructor
5556
"""
@@ -59,36 +60,30 @@ def Deserializer(object_list, **options):
5960
Model = _get_model(d["model"])
6061
data = {Model._meta.pk.attname : Model._meta.pk.to_python(d["pk"])}
6162
m2m_data = {}
62-
63+
6364
# Handle each field
6465
for (field_name, field_value) in d["fields"].iteritems():
65-
if isinstance(field_value, unicode):
66-
field_value = field_value.encode(options.get("encoding", settings.DEFAULT_CHARSET))
67-
66+
if isinstance(field_value, str):
67+
field_value = smart_unicode(field_value, options.get("encoding", settings.DEFAULT_CHARSET))
68+
6869
field = Model._meta.get_field(field_name)
69-
70+
7071
# Handle M2M relations
7172
if field.rel and isinstance(field.rel, models.ManyToManyRel):
72-
pks = []
7373
m2m_convert = field.rel.to._meta.pk.to_python
74-
for pk in field_value:
75-
if isinstance(pk, unicode):
76-
pks.append(m2m_convert(pk.encode(options.get("encoding", settings.DEFAULT_CHARSET))))
77-
else:
78-
pks.append(m2m_convert(pk))
79-
m2m_data[field.name] = pks
80-
74+
m2m_data[field.name] = [m2m_convert(smart_unicode(pk)) for pk in field_value]
75+
8176
# Handle FK fields
8277
elif field.rel and isinstance(field.rel, models.ManyToOneRel):
8378
if field_value:
8479
data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
8580
else:
8681
data[field.attname] = None
87-
82+
8883
# Handle all other fields
8984
else:
9085
data[field.name] = field.to_python(field_value)
91-
86+
9287
yield base.DeserializedObject(Model(**data), m2m_data)
9388

9489
def _get_model(model_identifier):
@@ -100,5 +95,5 @@ def _get_model(model_identifier):
10095
except TypeError:
10196
Model = None
10297
if Model is None:
103-
raise base.DeserializationError("Invalid model identifier: '%s'" % model_identifier)
98+
raise base.DeserializationError(u"Invalid model identifier: '%s'" % model_identifier)
10499
return Model

django/core/serializers/pyyaml.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ class Serializer(PythonSerializer):
1919
"""
2020
def end_serialization(self):
2121
yaml.dump(self.objects, self.stream, **self.options)
22-
22+
2323
def getvalue(self):
2424
return self.stream.getvalue()
2525

@@ -33,4 +33,4 @@ def Deserializer(stream_or_string, **options):
3333
stream = stream_or_string
3434
for obj in PythonDeserializer(yaml.load(stream)):
3535
yield obj
36-
36+

0 commit comments

Comments
 (0)