nat*_*002 6 python unicode cherrypy
我从提交模块生成的cherrypy脚本中收到以下错误。
ValueError:页面处理程序必须返回字节。如果您希望返回 unicode,请使用 tools.encode
我在我的配置中打开了 tool.encode 但我仍然收到这个错误。我允许用户通过 jQuery 表单插件上传内容。关于为什么我收到此错误的任何想法?
这是我的樱桃文件:
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()
Run Code Online (Sandbox Code Playgroud)
HTML:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='freelinreg_static/google.js'></script>
<script type='text/javascript' src='freelinreg_static/frontend.js'></script>
<script type='text/javascript' src='freelinreg_static/malsup.js'></script>
</head>
<body>
<form id="dataform" action="submit" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" id="myFile"/>
<input type="submit" id="data_submit" value="Continue"/>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
jQuery (frontend.js):
$(document).ready(function () {
(function () {
$('#dataform').ajaxForm({
url: "submit",
success: function (data) {
var $a_var = data['title'];
$('body').append($a_var);
}
});
return false;
})();
});
Run Code Online (Sandbox Code Playgroud)
我的情况是问题从 python2 切换到 python3 后开始。
已通过设置解决
'tools.encode.text_only': False
Run Code Online (Sandbox Code Playgroud)
在应用程序全局配置中。
希望能帮助到你
嗨,人们正在寻找答案。我遇到了同样的问题,但就我而言,这个小小的补充解决了一切。
return <some-json>.encode('utf8')
Run Code Online (Sandbox Code Playgroud)
您需要重新安排全局配置更新以在应用程序安装后进行:
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()
Run Code Online (Sandbox Code Playgroud)
因为您在配置更新命令后调用 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}
Run Code Online (Sandbox Code Playgroud)