在我的Django应用程序中,我使用suds库发出了soap请求。之后,我收到如下响应:
productdata = '<Root>
<Header>
<User>User</User>
<Password>Password</Password>
<OperationType>Response</OperationType>
</Header>
<Main>
<Hotel>
<HotelName>HotelName1</HotelName>
<TotalPrice>100</TotalPrice>
<Location>My Location</Location>
</Hotel>
<Hotel>
<HotelName>HotelName2</HotelName>
<TotalPrice>100</TotalPrice>
<Location>My Location</Location>
</Hotel>
</Main>
</Root> '
之后我将这些数据反序列化并保存到数据库中。这就是我反序列化数据的方式:
def etree_to_dict(t):
d = {t.tag: {} if t.attrib else None}
children = list(t)
if children:
dd = defaultdict(list)
for dc in map(etree_to_dict, children):
for k, v in dc.iteritems():
dd[k].append(v)
d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.iteritems()}}
if t.attrib:
d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems())
if t.text:
text = t.text.strip()
if children or t.attrib:
if text:
d[t.tag]['#text'] = text
else:
d[t.tag] = text
return d
这是我将数据保存到数据库:
e = ET.fromstring(productdata)
d = etree_to_dict(e)
hotels = d['Root']['Main']['Hotel']
for p in hotels:
product = Product()
p.hotelname = p['HotelName']
p.totalprice = p['TotalPrice']
p.location = p['Location']
p.save()
一切都很好。但是,当我收到Ü
标记中包含Location
符号的数据时,我收到了错误消息:
`UnicodeEncodeError`, `'ascii' codec can't encode character u'\xdc' in position 20134: ordinal not in range(128)`. `Unicode error hint: The string that could not be encoded/decoded was: ARK GÜELL A`.
Django traceback在这一行中说了这个问题:
e = ET.fromstring(productdata)
任何人都可以帮我解决这个问题。非常感谢!
答案 0 :(得分:1)
我认为你必须从UTF-8手动编码:
ElementTree.fromstring(productdata.encode('utf-8'))