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

时间:2013-11-26 10:57:38

标签: python unicode cherrypy

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

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

我在配置中打开了tool.encode,但我仍然收到此错误。我允许用户通过jQuery Form Plugin上传内容。为什么我收到这个错误的任何想法?

这是我的樱桃文件:

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:

<!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>

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;
    })();
});

3 个答案:

答案 0 :(得分:2)

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

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 = {},所以您覆盖了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}

答案 1 :(得分:1)

嗨,人们在寻找答案。 我遇到了同样的问题,但就我而言,这点补充解决了所有问题。

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

答案 2 :(得分:1)

我的情况是从p2切换到p3后问题开始了。

已通过设置解决

    'tools.encode.text_only': False

在应用程序全局配置中。

希望有帮助