gpt4 book ai didi

python - Django - UnicodeEncodeError

转载 作者:太空宇宙 更新时间:2023-11-03 16:51:56 26 4
gpt4 key购买 nike

在我的 Django 应用程序中,我使用 suds 库发出了肥皂请求。之后我收到如下响应:

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回溯说这一行有问题:

e = ET.fromstring(productdata)

谁能帮我解决这个问题。非常感谢!

最佳答案

我认为你必须从 UTF-8 手动对其进行编码:

ElementTree.fromstring(productdata.encode('utf-8'))

关于python - Django - UnicodeEncodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35768471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com