WSGI内容编码

dea*_*mon 0 python content-type http utf-8 character-encoding

如果我执行以下Python 3.1程序,我只会在浏览器中看到 而不是正确的字符.文件本身是UTF-8编码的,并且响应发送相同的编码.

from wsgiref.simple_server import make_server

page = "<html><body>äöü€ßÄÖÜ</body></html>"

def application(environ, start_response):
    start_response("200 Ok", [("Content-Type", "text/html; charset=UTF-8")])
    return page

httpd = make_server('', 8000, application)
print("Serving on port 8000...")
httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)

响应中正确设置了"UTF-8":

HTTP/1.0 200 Ok
Date: Mon, 09 Aug 2010 16:35:02 GMT
Server: WSGIServer/0.1 Python/3.1.1+
Content-Type: text/html; charset=UTF-8
Run Code Online (Sandbox Code Playgroud)

这有什么不对?

bob*_*nce 8

Python 3上的WSGI尚不存在.Web-SIG还没有得到关于如何在Python 3.x中处理字符串(字节/ unicode)的任何结论.

wsgiref主要是自动2to3转换; 即使除了3.x上的WSGI实际意味着什么因素之外,它仍然存在问题.不要依赖它作为WSGI应用程序在Python 3下如何工作的参考.

情况仍然如此,进入3.2发布周期令人尴尬和令人沮丧.

return page
Run Code Online (Sandbox Code Playgroud)

好吧,虽然WSGI for 3.x仍然是一个未知因素,但最值得赞同的是WSGI应用程序的响应体通常应该是字节而不是unicode,因为HTTP是基于字节的协议.是否接受Unicode字符串 - 如果是这样,它们将被转换为什么编码 - 仍然有待观察,所以避免问题并返回字节:

return [page.encode('utf-8')]
Run Code Online (Sandbox Code Playgroud)

(这[]是必需的,因为WSGI应用程序应该返回一个可输出的迭代,并且一次刷新一个项目.如果你自己传递一个字符串,那么它被用作一个可迭代的并且一次返回一个字符,这对性能来说太糟糕了.)