3

编码:

>>> from django.core import serializers
>>> objects = serializers.deserialize('xml', fixturestr)
>>> o = next(objects)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/marcintustin/oneclickrep/oneclickcosvirt/lib/python2.7/site-packages/django/core/serializers/xml_serializer.py", line 156, in next
    for event, node in self.event_stream:
  File "/usr/lib/python2.7/xml/dom/pulldom.py", line 232, in next
    rc = self.getEvent()
  File "/usr/lib/python2.7/xml/dom/pulldom.py", line 265, in getEvent
    self.parser.feed(buf)
  File "/usr/lib/python2.7/xml/sax/expatreader.py", line 210, in feed
    self._parser.Parse(data, isFinal)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xc5' in position 565: ordinal not in range(128)

fixturestr是一个 unicode 对象。消除非 ascii 字符不是一种选择。我怎样才能阻止反序列化器这样做?

4

2 回答 2

2

尝试使用smart_str将您的 unicode 对象转换为字符串:

from django.utils.encoding import smart_str
from django.core import serializers

objects = serializers.deserialize('xml', smart_str(fixturestr))
o = next(objects)
于 2013-10-29T21:36:54.993 回答
0

似乎如果传递了一个 unicode 对象,反序列化器将在某处尝试将其编码为 un​​icode。为避免这种情况,必须传递一个字节串:

objects = serializers.deserialize('xml', fixturestr.encode('utf8'))
于 2013-10-29T21:43:20.950 回答