在CherryPy中发送函数结果时的UnicodeDecodeError

时间:2015-01-27 20:10:24

标签: python unicode decode encode cherrypy

全部,

我想将一个字符串变量发送到网络应用程序。通常,当我在代码的“switch”部分内手动创建字符串时,我可以毫无问题地发送字符串。但是当我从函数中获取该字符串时,我收到错误。我的意思是,如果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 - - 在我的代码顶部。

您能告诉我您解决此问题的建议吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

这不是代码的问题,因为您可以看到堆栈跟踪在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)

编辑:让您更容易理解答案。您的代码可能在有问题的代码段之外,使用unicode消息引发异常。 CherryPy尝试为您的异常生成错误页面并失败,因为在这种情况下的堆栈跟踪是混乱的。异常消息是UTF-8字节还是unicode无关紧要。上面的代码只是一个提炼版本。

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