Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TwistedWeb:unicode编码问题_Python_Html_Http_Character Encoding_Twisted.web - Fatal编程技术网

Python TwistedWeb:unicode编码问题

Python TwistedWeb:unicode编码问题,python,html,http,character-encoding,twisted.web,Python,Html,Http,Character Encoding,Twisted.web,这可能是个愚蠢的问题,但我找不到答案。而且,它可能不是真正的扭曲特定的 我正在尝试为twisted.webwebserver编写一个资源,它应该为包含非ascii字符的页面提供服务。 根据,我所需要做的就是设置内容类型HTTP头并返回一个编码字符串。 不幸的是,页面显示无效字符 以下是代码(作为.rpy): “unicode测试” 从twisted.web.resource导入资源 类UnicodestResource(资源): “”“unicode测试资源。”“” isLeaf=True en

这可能是个愚蠢的问题,但我找不到答案。而且,它可能不是真正的扭曲特定的

我正在尝试为
twisted.web
webserver编写一个资源,它应该为包含非ascii字符的页面提供服务。 根据,我所需要做的就是设置
内容类型
HTTP头并返回一个编码字符串。 不幸的是,页面显示无效字符

以下是代码(作为
.rpy
):

“unicode测试”
从twisted.web.resource导入资源
类UnicodestResource(资源):
“”“unicode测试资源。”“”
isLeaf=True
encoding=“utf-8”
def render_GET(自我,请求):
text=u“unicode测试”
raw=u“Unicode编码测试

{t}

”。格式(t=text) enc=raw.encode(自编码) request.setHeader(“内容类型”、“文本/html;字符集=“+self.encoding”) 返回enc 资源=UnicodestResource()
结果(不含html)是:
unicode测试ÃÃÃüÃ

这是由服务器和客户端之间的编码不匹配引起的吗

我使用的是python 2.7.12和twisted 17.1.0。该页面已使用firefox访问

对不起,我的英语很糟糕

谢谢

编辑:我发现了问题。我假设使用
ResourceScript
处理器的
twisted.web.static.File
将使用运行reactor的文件中指定的编码。 显然情况并非如此。 在每个文件的顶部添加
#-*-编码:utf-8-*-
修复了该问题

"""a unicode test"""
from twisted.web.resource import Resource

class UnicodeTestResource(Resource):
    """A unicode test resource."""
    isLeaf = True
    encoding = "utf-8"

    def render_GET(self, request):
            text = u"unicode test\n ä ö ü ß"
            raw = u"<HTML><HEAD><TITLE>Unicode encoding test</TITLE><HEAD><BODY><P>{t}</P></BODY></HTML>".format(t=text)
            enc = raw.encode(self.encoding)
            request.setHeader("Content-Type", "text/html; charset=" + self.encoding)
            return enc

resource = UnicodeTestResource()