【问题标题】:Django - UnicodeEncodeError [duplicate]Django - UnicodeEncodeError [重复]
【发布时间】:2016-06-16 13:26:50
【问题描述】:

在我的 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 traceback 在这一行说这个问题:

e = ET.fromstring(productdata)

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

【问题讨论】:

    标签: python django elementtree


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答,我将e = ET.fromstring(productdata) 更改为e = ET.fromstring(productdata.decode('utf-8')),但我仍然有同样的错误
    • 抱歉,我想我把encodedecode 弄混了。请咨询encode
    猜你喜欢
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 2017-12-08
    • 2015-09-16
    • 2016-09-25
    • 2017-08-04
    • 2012-02-09
    相关资源
    最近更新 更多