django反序列化尝试将输入编码为ascii?

时间:2013-10-29 21:28:40

标签: python xml django unicode python-unicode

代码:

>>> 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字符不是一种选择。如何阻止反序列化程序执行此操作?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

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

objects = serializers.deserialize('xml', fixturestr.encode('utf8'))