我尝试使用python2.7.1、jinja2.5.2和cherrypy3.1.2运行一个网站。使用jinutja-8编码模板。我注意到这些模板中的一些字符正在变成问号和其他胡言乱语。如果我尝试直接渲染没有Jinja的模板,我不会注意到这个问题。我发现我可以通过在所有处理程序的输出上调用.encode("utf-8")
来修复它,但这会让人恼火,因为它会扰乱我的源代码。有人知道为什么会这样吗?或者该怎么办?我做了一个小脚本来演示这个问题。“的”字符.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())
jinja2只支持Unicode。当客户端发送no
Accept-Header
时,cherrypy似乎通常使用utf-8作为输出编码,但是当它为空时,它会回到iso-8859-1。在我可以使用这样的编码工具来解决问题:
示例
^{pr2}$从CherryPy tutorial:
听起来像你的答案。在
相关问题 更多 >
编程相关推荐