开发者

UnicodeEncodeError when trying to convert Django models to XML

开发者 https://www.devze.com 2023-02-06 21:09 出处:网络
I found a python program: Export Django database to xml file that converts django models to a xml representation. I get these errors when trying to run the progra开发者_如何学JAVAm. My models contain

I found a python program: Export Django database to xml file that converts django models to a xml representation. I get these errors when trying to run the progra开发者_如何学JAVAm. My models contain some text written in French.

Traceback (most recent call last):
  File "xml_export.py", line 71, in <module>
  writer.content(value)
File "xml_export.py", line 41, in content
  self.output += str(text)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3:
ordinal not in range(128) 


It looks like your variable text contains a non-ASCII string.

See:

>>> mystring = u"élève"
>>> mystring
u'\xe9l\xe8ve'
>>> str(mystring)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)

So, you first need to encode your string into UTF-8:

>>> str(mystring.encode("utf-8"))
'\xc3\xa9l\xc3\xa8ve'

Or, if (as the comments show) text may contain other variable types besides strings, use

self.output += unicode(mystring).encode("utf-8")


Seriously, don't use the linked code. It's terrible, and appears to have been written by someone with absolutely no knowledge of unicode, character encodings, or even how to build up an XML document. String concatentation? Really?

Just don't use it.


Did you tried to use the built-in command :

./manage.py dumpdata --format xml

The way you used unicode in u'élève' is ok, so this should work (normalement...).

0

精彩评论

暂无评论...
验证码 换一张
取 消