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

2024-09-27 00:16:45 发布

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

所有人

我想发送一个字符串变量到web应用程序。通常,当我在代码的“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()

错误是:

^{pr2}$

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

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

你能谈谈你解决这个问题的建议吗?在

提前谢谢。在


Tags: path字符串代码importconfig应用程序编码os
1条回答
网友
1楼 · 发布于 2024-09-27 00:16:45

这不是代码的问题,因为您可以看到堆栈跟踪以get_error_page结尾。这是CherryPy bug(或者Pythontraceback.format_exc()的bug,因为它会产生相当大的混乱),我在几年前也遇到过。我已经向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并不重要。上面的代码只是一个精简版本。在

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

相关问题 更多 >

    热门问题