如何通过plone浏览器代理web服务,生成utf8编码的xml

2024-03-29 08:23:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个plone3.3站点,它从restfulweb服务检索信息;该服务返回utf-8编码的xml数据。请求通过一个特殊的浏览器发送(对于这个问题,我们称之为@@proxy)。只要不返回非ASCII数据,一切正常。在

浏览器的get方法如下所示:

def get(self, thedict=None):
    """
    reduced version for stackoverflow
    """
    context = self.context
    request = context.request
    response = request.response
    if thedict is None:
        thedict = request.form
    theurl = '?'.join((basejoin(SERVICEBASE, thedict['path']),
                       urlencode(auth_data),
                       ))
    fo = urlopen(theurl)
    code = fo.code
    headers = fo.info().headers
    for line in headers:
        name, text = line.split(':', 1)
        response.setHeader(name, text.strip())    # trailing \r\n
    text = unicode(fo.read(), 'utf-8')
    # --- debugging only ... -- 8< ----- 8< ----- 8< ----- 8< ----- 8<
    CHARSHERE = set(list(text))
    funnychars = CHARSHERE.difference(XMLCHARS)
    if funnychars:
        funnychars = u''.join(tuple(funnychars))
        logger.info('funny chars: %r' % funnychars)
    elif 1:
        logger.info('funny chars: none')
    # --- ... debugging only -- >8 ----- >8 ----- >8 ----- >8 ----- >8
    response.setBody(text.encode('utf-8'))

首先,我没有做任何关于编码的事情(unicodeencode)。然而,这似乎是必要的;当包含非ASCII数据(例如INFO proxy@@w3l funny chars: u'\xdf')时,浏览器不喜欢结果。当我直接尝试相同的请求时(发送到theurl,而不是通过我的@@proxy浏览器),它就可以工作了。这个问题并不取决于网络浏览器,也就是说,Firefox和IE咳嗽都有。在

有一个值为“text/xml;charset=UTF-8”的Content-Type头;在分号后面插入空格字符不会改变任何内容。在

编辑:Seamonkey如是说:

^{pr2}$

(英语:xml处理错误:找不到元素;行1,列1)

因为我不是该服务的作者,所以我不完全确定数据是否真的是真的UTF-8(尽管HTTP报头和<?xml ...>行是这样说的)。在

我的错误是什么?我该怎么做才能找到问题?我是否遗漏了关于Zope响应对象和/或urllib2.urlopen的重要信息?在

我也试过类似的东西(浓缩):

fo = urlopen(theurl)
raw = fo.read().strip()
try:
    text = unicode(raw, 'utf-8')
    logger.info('Text passes off as utf-8')
except Exception, e:
    logger.info('no valid utf-8:')
    logger.exception(e)
    text = unicode(raw, 'latin-1')

。。。或者反过来说,我从来没有出现过任何解码错误。在

我将“原始”数据写入一个文件(open(filename, 'wb')),我用vim(set enc? fenc?)检查了这个文件,得到了utf-8。在

我真是束手无策。在


Tags: 数据textinforesponserequestunicode浏览器xml