【发布时间】:2016-12-30 11:02:18
【问题描述】:
鉴于具有多种表示(媒体类型)的资源不使用自定义 CherryPy“工具”来处理“接受”HTTP 标头的解释和响应实体主体的序列化,CherryPy 引发以下ValueError在适当设置“Content-Type”HTTP 标头后从页面处理程序返回内容时出现异常,但仅适用于某些媒体类型:
ValueError:页面处理程序必须返回字节。如果您希望返回 unicode,请使用 tools.encode。
例子:
contentType = tools.accept.callable(media = ['application/json', 'text/html'])
if contentType == 'application/json':
return json.dumps(studies)
elif contentType == 'text/html':
...
这适用于两种媒体类型,尽管 JSON 表示会被错误地声明为 HTML(默认)。
contentType = tools.accept.callable(media = ['application/json', 'text/html'])
response.headers['Content-Type'] = "{mediaType}; charset=utf-8".format(mediaType = contentType)
if contentType == 'application/json':
return json.dumps(studies)
elif contentType == 'text/html':
...
这里将 JSON 内容作为字符串返回时会引发上述异常。
尝试确保确实启用了tools.encode 并将tools.encode.encoding 显式设置为utf-8(即使它是默认值)失败。事情适用于 HTML 表示,所以它似乎也适用于 JSON 表示。
目前tools.encode 的文档似乎相当稀少,因此最好的方法不是很明显。
【问题讨论】:
标签: cherrypy