繁体   English   中英

GAE Python:从XML文件导入UTF-8字符到数据库模型

[英]GAE Python: Importing UTF-8 Characters from an XML file to a database model

我正在从在线来源解析XML文件,但是在读取utf-8字符时遇到了麻烦。 现在,我已经阅读了处理类似问题的其他一些问题,但是到目前为止,所有解决方案都无效。 当前代码如下。

class XMLParser(webapp2.RequestHandler):

def get(self):

        url = fetch('some.xml.online')

        xml = parseString(url.content)

        vouchers = xml.getElementsByTagName("VoucherCode")

        for voucher in vouchers:

          if voucher.getElementsByTagName("ActivePartnership")[0].firstChild.data == "true":

            coupon = Coupon()
            coupon.description = str(voucher.getElementsByTagName("Description")[0].firstChild.data.decode('utf-8'))
            coupon.prov_key = str(voucher.getElementsByTagName("Id")[0].firstChild.data)
            coupon.put()
            self.redirect('/admin/coupon')

我从中得到的错误显示在下面。 这是由描述字段中的“ü”引起的,稍后在使用数据时我还将需要显示它。

在get coupon.description = str(voucher.getElementsByTagName(“ Description”)[0] .firstChild.data.decode中的文件“ C:\\ Users \\ Vincent \\ Documents \\ www \\ Sparkompass \\ Website \\ main.py”中,第217行('utf-8'))文件“ C:\\ Python27 \\ lib \\ encodings \\ utf_8.py”,第16行,解码返回codecs.utf_8_decode(input,errors,True)UnicodeEncodeError:'ascii'编解码器无法编码字符u'\\ xfc'在位置16:序数不在范围内(128)

如果我删除说明,一切都会正常进行。 在数据库模型定义中,我将描述定义如下:

description = db.StringProperty(multiline=True)

尝试2

我也试图这样做:

coupon.description = str(voucher.getElementsByTagName("Description")[0].firstChild.data).decode('utf-8')

这也给了我:

UnicodeEncodeError:'ascii'编解码器无法在位置16编码字符u'\\ xfc'(序数不在范围内)(128)

任何帮助将不胜感激!

UPDATE

XML文件包含德语,这意味着其中的更多字符都是UTF-8字符。 因此,理想情况下,我现在正在考虑最好在较高级别(例如在

xml = parseString(url.content)

但是到目前为止,我也没有做到这一点。 目的是获取ascii中的字符,因为这是GAE要求将其注册为数据库模型中的字符串。

>>> u"ü".decode("utf-8")

UnicodeEncodeError

>>> u"ü".encode("utf-8") 

'\\ XC3 \\命苦'

>>> u"ü".encode("utf-8").decode("utf-8")

U '\\ XFC'

>>> str(u"ü".encode("utf-8").decode("utf-8"))

UnicodeEncodeError

>>> str(u"ü".encode("utf-8"))

'\\ XC3 \\命苦'

您需要哪种编码?

您还可以使用:

string2 = cgi.escape(string).encode("latin-1", "xmlcharrefreplace") 

这会将所有非拉丁1字符替换为xml实体。

我现在通过将描述更改为TextProperty来解决该问题,该操作没有任何错误。 我知道我在执行此操作时将无法进行排序或过滤,但出于描述的考虑,这应该可以。

背景信息: https : //developers.google.com/appengine/docs/python/datastore/typesandpropertyclasses#TextProperty

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM