You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为CherryPy静态文件设置UTF-8字符集编码?

在CherryPy中为静态文件添加UTF-8字符集编码

你的问题出在CherryPy的tools.encode工具默认不会处理静态文件请求——静态文件服务是直接返回文件内容,跳过了部分工具链。可以通过以下几种方式解决:

方法一:指定静态文件的Content-Type映射

在配置中添加tools.staticdir.content_types,直接为HTML文件设置带字符集的MIME类型:

class StaticServer(object):
    pass

config = {
    '/': {
        'tools.encode.on': True,
        'tools.encode.encoding': 'utf-8',
        'tools.staticdir.on': True,
        'tools.staticdir.dir': fullpath,
        'tools.staticdir.index': 'index.html',
        'tools.staticdir.content_types': {
            'html': 'text/html; charset=utf-8'
        },
        'error_page.default': error_page
    }
}

cherrypy.tree.mount(StaticServer(), "/", config=config)

该配置会让所有.html文件的响应头Content-Type变为text/html; charset=utf-8,浏览器就能正确识别UTF-8编码。

方法二:自定义工具强制添加字符集头

如果需要对更多文本类文件(如JS、CSS)统一设置字符集,可以添加自定义工具拦截响应并补充字符集:

def add_charset_header():
    response = cherrypy.response
    if 'Content-Type' in response.headers:
        ct = response.headers['Content-Type']
        # 针对文本类MIME类型自动补充字符集
        text_types = ['text/', 'application/javascript', 'application/json', 'text/css']
        if any(ct.startswith(t) for t in text_types) and 'charset' not in ct.lower():
            response.headers['Content-Type'] = f"{ct}; charset=utf-8"

# 注册自定义工具
cherrypy.tools.custom_charset = cherrypy.Tool('before_finalize', add_charset_header)

config = {
    '/': {
        'tools.encode.on': True,
        'tools.encode.encoding': 'utf-8',
        'tools.staticdir.on': True,
        'tools.staticdir.dir': fullpath,
        'tools.staticdir.index': 'index.html',
        'tools.custom_charset.on': True,
        'error_page.default': error_page
    }
}

cherrypy.tree.mount(StaticServer(), "/", config=config)

额外注意

确保你的index.html文件本身是以UTF-8无BOM格式保存的,否则即使响应头正确,浏览器也可能解析错误。

内容的提问来源于stack exchange,提问作者Bart Friederichs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 23:22:37