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

标签 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())

最佳答案

jinja2 仅适用于 Unicode。貌似cherrypy一般在客户端没有发送Accept-Header的时候使用utf-8作为输出编码,但是当它为空的时候回退到iso-8859-1。

tools.encode.encoding: If specified, the tool will error if the response cannot be encoded with it. Otherwise, the tool will use the 'Accept-Charset' request header to attempt to provide suitable encodings, usually attempting utf-8 if the client doesn't specify a charset, but following RFC 2616 and trying ISO-8859-1 if the client sent an empty 'Accept-Charset' header.

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"
»

关于python - CherryPy 无法正确处理 Jinja2 模板中的非 ASCII 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4915411/

相关文章:

python - 计算两个矩阵的余弦相似度

python - 使用正则表达式删除以数字开头的字符串中的第一个单词

c - 在UTF-16、UTF-16BE、UTF-16LE中,UTF-16的字节序是计算机的字节顺序吗?

javascript - python3 打印函数发出 'ascii' codec can't encode character 错误

java - 为什么Java的CharsetEncoder定义.onMalformedInput()/CharsetDecoder定义.onUnmappableCharacter()?

python - 查找列表中丢失的字母(仅小写或大写)

python - pandas 更有效地从 csv 创建字典对象以作为 post 请求发送

string - 组合变音符号出现在代码点之后的顺序是否重要?

java - 正确的字符集 |

c++ - 该程序是否在所有标准系统上显示四套牌(♠♣♥♦)?