我想将 HTML 页面发送到编码为 UTF-8 的 Web 浏览器。但是以下示例失败:
from wsgiref.simple_server import make_server
def app(environ, start_response):
output = "<html><body><p>Räksmörgås</p></body></html>".encode('utf-8')
start_response('200 OK', [
('Content-Type', 'text/html'),
('Content-Length', str(len(output))),
])
return output
port = 8000
httpd = make_server('', port, app)
print("Serving on", port)
httpd.serve_forever()
这是回溯:
Serving on 8000
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/wsgiref/handlers.py", line 75, in run
self.finish_response()
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/wsgiref/handlers.py", line 116, in finish_response
self.write(data)
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/wsgiref/handlers.py", line 202, in write
"write() argument must be a string or bytes"
如果我删除编码并简单地返回 python 3 unicode 字符串,则 wsgiref 服务器似乎以浏览器在请求标头中指定的任何字符集进行编码。但是,我希望自己拥有这种控制权,因为我怀疑我是否可以期望所有 WSGI 服务器都这样做。我应该怎么做才能返回一个 UTF-8 编码的 HTML 页面?
谢谢!