CherryPy无法正确处理Jinja2模板中的非ASCII字符

时间:2011-02-06 19:01:57

标签: python unicode character-encoding cherrypy jinja2

我正在尝试使用Python 2.7.1,Jinja 2.5.2和CherryPy 3.1.2运行网站。我使用的Jinja模板是UTF-8编码的。我注意到这些模板中的一些字符变成了问号和其他乱码。如果我尝试在没有Jinja的情况下直接渲染模板,我没有注意到这个问题。我发现我可以通过在所有处理程序的输出上调用.encode("utf-8")来修复它,但这会让我很烦,因为它会使我的源代码变得混乱。有谁知道为什么会发生这种情况或该怎么办?我做了一个小脚本来演示这个问题。 “char.txt”文件是一个2字节的文件,仅由UTF-8编码的“»”字符组成。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, jinja2, cherrypy
jinja2env = jinja2.Environment(loader=jinja2.FileSystemLoader("."))

class Test(object):
    def test1(self):
        #doesn't work
        #curl "http://example.com/test1"
        #?
        return jinja2env.get_template("char.txt").render()
    test1.exposed = True

    def test2(self):
        #works
        #curl "http://example.com/test2"
        #»
        return open("char.txt").read()
    test2.exposed = True

    def test3(self):
        #works, but it is annoying to have to call this extra function all the time
        #curl "http://example.com/test3"
        #»
        return jinja2env.get_template("char.txt").render().encode("utf-8")
    test3.exposed = True

cherrypy.config["server.socket_port"] = 8500
cherrypy.quickstart(Test())

2 个答案:

答案 0 :(得分:6)

jinja2仅适用于Unicode。似乎cherrypy通常使用utf-8作为输出编码,当客户端不发送Accept-Header时,但当它为空时会回落到iso-8859-1。

  

tools.encode.encoding:如果指定,   如果响应,该工具将出错   不能用它编码。除此以外,   该工具将使用'Accept-Charset'   请求标头尝试提供   适当的编码,通常是尝试   utf-8如果客户端没有指定a   charset,但遵循RFC 2616和   如果客户端发送,则尝试ISO-8859-1   一个空的'Accept-Charset'标题。

     

http://www.cherrypy.org/wiki/BuiltinTools#tools.encode

我可以通过使用这样的编码工具解决问题:

cherrypy.config["tools.encode.on"] = True
cherrypy.config["tools.encode.encoding"] = "utf-8"

实施例

$ curl "http://127.0.0.1:8500/test1"
»
$ curl "http://127.0.0.1:8500/test2"
»
$ curl "http://127.0.0.1:8500/test3"
»

答案 1 :(得分:2)

来自CherryPy tutorial

  

tools.encode:自动转换   本机Python的响应   Unicode字符串格式适合一些   编码(Latin-1或UTF-8,for   例子)。

这听起来像是你的答案。