【问题标题】:UnicodeDecodeError when sending the result of a function in CherryPy在 CherryPy 中发送函数结果时出现 UnicodeDecodeError
【发布时间】:2015-01-27 20:10:24
【问题描述】:

大家好,

我想向网络应用发送一个字符串变量。通常,当我在代码的“开关”部分手动创建它时,我可以毫无问题地发送一个字符串。但是当我从函数中获取该字符串时,我得到了一个错误。我的意思是,如果 counterstring='12.3' ,没有问题。但是如果counterstring=ReadCounter(),就有问题了。

这是代码的实际部分:

import cherrypy
import webbrowser
import os
import json
import sys

MEDIA_DIR = os.path.join(os.path.abspath("."), u"media")

class AjaxApp(object):
    @cherrypy.expose
    def index(self):
        return open(os.path.join(MEDIA_DIR, u'index.html'))

    @cherrypy.expose
    def switch(self):
        counterstring=ReadCounter()
        return counterstring

config = {'/media':
                {'tools.staticdir.on': True,
                 'tools.staticdir.dir': MEDIA_DIR,
                }
        }

def open_page():
    webbrowser.open("http://127.0.0.1:8080/")
    cherrypy.engine.subscribe('start', open_page)
    cherrypy.tree.mount(AjaxApp(), '/', config=config)
    cherrypy.engine.start()

错误是:

    ERROR:cherrypy.error.55086800:[27/Jan/2015:02:47:09]  Traceback (most recent call last):
      File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 589, in run
        self.respond(pi)
      File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 690, in respond
        self.handle_error()
      File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 767, in handle_error
        self.error_response()
      File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 401, in set_response
        message=self._message)
      File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 407, in get_error_page
        return get_error_page(*args, **kwargs)
      File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 535, in get_error_page
        return result.encode('utf-8')
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 2271: ordinal not in range(128)

ERROR:cherrypy.error.42068624:[29/Jan/2015:09:14:46]  Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 589, in run
    self.respond(pi)
  File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 690, in respond
    self.handle_error()
  File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 767, in handle_error
    self.error_response()
  File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 402, in set_response
    message=self._message)
  File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 408, in get_error_page
    return get_error_page(*args, **kwargs)
  File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 536, in get_error_page
    return result.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 2294: ordinal not in range(128)

我尝试了很多关于编码/解码的事情。我在应用程序中为字符串添加了编码/解码函数

我有 # -- 编码:utf-8 -- 在我的代码顶部。

能否请您谈谈解决此问题的建议?

提前致谢。

【问题讨论】:

  • 什么是“反串”? ASCII 格式的字符串?
  • counterstrıng 是在该行创建的字符串。它必须是 utf-8,因为顶部有声明。

标签: python unicode decode encode cherrypy


【解决方案1】:

这不是您的代码的问题,因为您可以看到堆栈跟踪以get_error_page 结尾。这是 CherryPy 错误(或 Python traceback.format_exc() 的错误,因为它会产生相当混乱),我之前也遇到过。我已经向 CherryPy 提交了错误报告,#1356

因此,如果您可以避免 unicode 异常消息。其他解决方法是设置自定义错误页面处理程序:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import cherrypy


def errorPage(**kwargs):
  temaplte = cherrypy._cperror._HTTPErrorTemplate
  return temaplte % kwargs


config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8,
    # here's the workaround
    'error_page.default' : errorPage
  }
}


class App:

  @cherrypy.expose
  def index(self):
    return '''
      <a href='/errorPageStr'>errorPageStr</a><br/>
      <a href='/errorPageUnicode'>errorPageUnicode</a>
    '''

  @cherrypy.expose
  def errorPageStr(self):
    raise RuntimeError('Şansal Birbaş')

  @cherrypy.expose
  def errorPageUnicode(self):
    raise RuntimeError(u'Şansal Birbaş')


if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

编辑:为了更容易理解答案。您的代码(可能在所讨论的 sn-p 之外的某个地方)引发了带有 unicode 消息的异常。 CherryPy 尝试为您的异常生成错误页面并失败,因为在这种情况下堆栈跟踪是混乱的。异常消息是 UTF-8 字节还是 unicode 都没有关系。上面的代码只是一个提炼的版本。

您需要在代码中设置自定义错误处理程序,以便查看您的原始异常

【讨论】:

  • 我的函数 ReadCounter() 只产生一个实数字符串。我的意思是,它总是采用浮点数格式,例如“234.54”。根据您的建议,我使用了 unicode_escape。但它没有成功。在您上面的代码中,据我了解,我们只是根据字符串生成一个新的自定义错误显示。但我想要的是完全摆脱这个问题。
  • 我注意到我在上面写了错误输出。我编辑了那个。只是同样的错误。
  • @ŞansalBirbaş 我添加了关于原始异常的说明。看看吧。
猜你喜欢
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
相关资源
最近更新 更多