Python Cherrypy:500 ValueError:页面处理程序必须返回字节

Python Cherrypy:500 ValueError:页面处理程序必须返回字节,python,unicode,cherrypy,Python,Unicode,Cherrypy,我从提交模块生成的cherrypy脚本中得到以下错误 ValueError:页处理程序必须返回字节。如果希望返回unicode,请使用tools.encode 我在配置中打开了tool.encode,但仍然出现此错误。我允许用户通过jQuery表单插件上传内容。有没有想过为什么我会犯这个错误 这是我的cherrypy文件: class Root(object): @cherrypy.expose def index(self) return open('/home/joesto

我从提交模块生成的cherrypy脚本中得到以下错误

ValueError:页处理程序必须返回字节。如果希望返回unicode,请使用tools.encode

我在配置中打开了tool.encode,但仍然出现此错误。我允许用户通过jQuery表单插件上传内容。有没有想过为什么我会犯这个错误

这是我的cherrypy文件:

class Root(object):    

@cherrypy.expose
def index(self)
    return open('/home/joestox/webapps/freelinreg_static/index.html')

@cherrypy.expose
def submit(self, myfile):

    cherrypy.session['myfile'] = myfile
    data_name = myfile.filename

    #Send back to JQuery with Ajax
    #Put in JSON form
    data_name= json.dumps(dict(title = data_name))
    cherrypy.response.headers['Content-Type'] = 'application/json'

    return data_name



cherrypy.config.update({
    'tools.staticdir.debug': True,
    'log.screen': True,
    'server.socket_host': '127.0.0.1',
    'server.socket_port': *****,
    'tools.sessions.on': True,
    'tools.encode.on': True,
    'tools.encode.encoding': 'utf-8',
})

config = {
}

cherrypy.tree.mount(Root(), '/', config=config)
cherrypy.engine.start()
HTML:


您需要重新安排全局配置更新,以便在应用程序装载后进行:

config = {
}

cherrypy.tree.mount(Root(), '/', config=config)

cherrypy.config.update({
    'tools.staticdir.debug': True,
    'log.screen': True,
    'server.socket_host': '127.0.0.1',
    'server.socket_port': *****,
    'tools.sessions.on': True,
    'tools.encode.on': True,
    'tools.encode.encoding': 'utf-8'
})

cherrypy.engine.start()
因为您在config update命令后调用config={},所以覆盖了
Root
应用程序的更新设置

另外,将提交功能更改为:

@cherrypy.expose
@cherrypy.tools.json_out
def submit(self, myfile):
    cherrypy.session['myfile'] = myfile

    # Return dict, which will be autoconverted to JSON
    # by the json_out tool (see decorator above)
    return {'title': myfile.filename}

嗨,人们在寻找答案。 我也有同样的问题,但在我的情况下,这个小小的增加解决了一切

return <some-json>.encode('utf8')
return.encode('utf8')

我的案例问题是在从python2切换到python3之后开始的

通过设置

    'tools.encode.text_only': False
在应用程序全局配置中


希望有帮助

谢谢你的提示!很有道理!不幸的是,我仍然得到同样的500值错误。它起作用了!是否仍要将数据作为JSON dict发送回jQuery?现在jQuery似乎没有意识到它是一个JSON dict。。。JSONobj=JSON.parse(数据);警报(JSONobj.title);要从dict返回json,请使用json_out工具,而不是使用json_out工具,只需返回一个dict@webKnjaZ很好地解决了我的问题,我也犯了同样的错误,这两个词也解决了,所以我很高兴,这不是架构上最好的方式。在看了其他答案后,这对我来说是有效的。非常感谢。
return <some-json>.encode('utf8')
    'tools.encode.text_only': False